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

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

function formatListingPrice(price: number): string {
  return `£${price.toLocaleString()}`;
}

function formatListingHeadline(listing: ActualListing, t: TFunction): string | null {
  const parts: string[] = [];
  if (listing.bedrooms != null) parts.push(t('common.bedsCount', { count: listing.bedrooms }));
  if (listing.bathrooms != null) parts.push(t('common.bathsCount', { count: listing.bathrooms }));
  if (listing.property_sub_type) parts.push(listing.property_sub_type);
  else if (listing.property_type) parts.push(listing.property_type);
  return parts.length > 0 ? parts.join(' · ') : null;
}

export const ListingPopupSingleContent = memo(function ListingPopupSingleContent({
  listing,
}: {
  listing: ActualListing;
}) {
  const { t } = useTranslation();
  return (
    <a
      href={listing.listing_url}
      target="_blank"
      rel="noopener noreferrer"
      className="block px-3 py-2"
    >
      {listing.asking_price != null && (
        <div className="text-base font-bold text-teal-600 dark:text-teal-400">
          {formatListingPrice(listing.asking_price)}
          {listing.price_qualifier ? (
            <span className="ml-1 text-xs font-medium text-warm-500 dark:text-warm-400">
              {listing.price_qualifier}
            </span>
          ) : null}
        </div>
      )}
      {formatListingHeadline(listing, t) && (
        <div className="text-xs text-warm-700 dark:text-warm-200 mt-0.5">
          {formatListingHeadline(listing, t)}
        </div>
      )}
      {listing.address && (
        <div className="text-xs text-warm-500 dark:text-warm-400 mt-0.5 line-clamp-2">
          {listing.address}
        </div>
      )}
      {listing.postcode && (
        <div className="text-[11px] text-warm-400 dark:text-warm-500 mt-0.5">
          {listing.postcode}
        </div>
      )}
      {listing.floor_area_sqm != null && (
        <div className="text-[11px] text-warm-500 dark:text-warm-400 mt-0.5">
          {Math.round(listing.floor_area_sqm)} sqm
          {listing.asking_price_per_sqm != null
            ? ` · £${Math.round(listing.asking_price_per_sqm).toLocaleString()}/sqm`
            : ''}
        </div>
      )}
      {listing.features.length > 0 && (
        <ul className="mt-1.5 text-[11px] text-warm-600 dark:text-warm-300 list-disc pl-4 space-y-0.5">
          {listing.features.slice(0, 3).map((feature, idx) => (
            <li key={idx} className="line-clamp-1">
              {feature}
            </li>
          ))}
        </ul>
      )}
      <div className="mt-1.5 text-[11px] text-teal-600 dark:text-teal-400 font-medium">
        Open listing ↗
      </div>
    </a>
  );
});

export const ListingClusterPopupContent = memo(function ListingClusterPopupContent({
  count,
  listings,
}: {
  count: number;
  listings: ActualListing[];
}) {
  const { t } = useTranslation();
  const visibleCount = listings.length;
  return (
    <div>
      <div className="border-b border-warm-200 px-3 py-2 dark:border-warm-700">
        <div className="text-base font-bold text-red-600 dark:text-red-400">
          {count.toLocaleString()} listings
        </div>
        <div className="text-[11px] text-warm-500 dark:text-warm-400">
          {visibleCount > 0
            ? `Showing ${visibleCount.toLocaleString()} of ${count.toLocaleString()}`
            : 'Grouped near this map position'}
        </div>
      </div>
      {visibleCount > 0 && (
        <div className="max-h-80 overflow-y-auto py-1">
          {listings.map((listing, idx) => {
            const headline = formatListingHeadline(listing, t);
            return (
              <a
                key={`${listing.listing_url}-${idx}`}
                href={listing.listing_url}
                target="_blank"
                rel="noopener noreferrer"
                className="block border-b border-warm-100 px-3 py-2 last:border-b-0 hover:bg-warm-50 dark:border-warm-700 dark:hover:bg-warm-700/60"
              >
                <div className="flex items-start justify-between gap-3">
                  <div className="min-w-0">
                    <div className="text-sm font-semibold text-teal-700 dark:text-teal-300">
                      {listing.asking_price != null
                        ? formatListingPrice(listing.asking_price)
                        : 'Listing'}
                    </div>
                    {headline && (
                      <div className="mt-0.5 truncate text-xs text-warm-700 dark:text-warm-200">
                        {headline}
                      </div>
                    )}
                    {listing.address && (
                      <div className="mt-0.5 line-clamp-1 text-[11px] text-warm-500 dark:text-warm-400">
                        {listing.address}
                      </div>
                    )}
                  </div>
                  {listing.postcode && (
                    <div className="shrink-0 text-[11px] font-medium text-warm-400 dark:text-warm-500">
                      {listing.postcode}
                    </div>
                  )}
                </div>
              </a>
            );
          })}
        </div>
      )}
    </div>
  );
});
