import { memo } from 'react';
import { useTranslation } from 'react-i18next';

import type { Development } from '../../types';

/** Turn a raw server status like "full-planning-permission" into "Full planning permission". */
function prettifyStatus(value: string): string {
  const cleaned = value.replace(/[-_]+/g, ' ').trim();
  if (!cleaned) return value;
  return cleaned.charAt(0).toUpperCase() + cleaned.slice(1);
}

export const DevelopmentPopupContent = memo(function DevelopmentPopupContent({
  development,
}: {
  development: Development;
}) {
  const { t } = useTranslation();
  const min = development.min_dwellings ?? null;
  const max = development.max_dwellings ?? null;

  let dwellings: string | null = null;
  if (min != null && max != null) {
    dwellings =
      min === max
        ? t('newDevelopments.homesExact', { count: max })
        : t('newDevelopments.homesRange', { min, max });
  } else if (max != null) {
    dwellings = t('newDevelopments.homesUpTo', { count: max });
  } else if (min != null) {
    dwellings = t('newDevelopments.homesExact', { count: min });
  }

  const sourceLabel =
    development.source === 'homes-england'
      ? t('newDevelopments.sourceHomesEngland')
      : t('newDevelopments.sourceBrownfield');

  return (
    <div className="max-w-[260px] px-3 py-2">
      <div className="text-sm font-bold text-blue-700 dark:text-blue-400">
        {development.name || t('newDevelopments.title')}
      </div>
      {dwellings && (
        <div className="mt-0.5 text-xs font-medium text-warm-700 dark:text-warm-200">
          {dwellings}
        </div>
      )}
      {development.planning_status && (
        <div className="mt-0.5 text-xs text-warm-500 dark:text-warm-400">
          {t('newDevelopments.planningStatus')}: {prettifyStatus(development.planning_status)}
        </div>
      )}
      {development.local_authority && (
        <div className="mt-0.5 text-[11px] text-warm-500 dark:text-warm-400">
          {t('newDevelopments.localAuthority')}: {development.local_authority}
        </div>
      )}
      <div className="mt-1 text-[11px] text-warm-400 dark:text-warm-500">{sourceLabel}</div>
      {development.url && (
        <a
          href={development.url}
          target="_blank"
          rel="noopener noreferrer"
          className="mt-1.5 block text-[11px] font-medium text-blue-600 dark:text-blue-400"
        >
          {t('newDevelopments.viewRecord')}
        </a>
      )}
    </div>
  );
});
