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

import type { FeatureMeta, MapFlyToOptions } from '../../types';
import { useTranslatedModes } from '../../hooks/useTravelTime';
import { ts } from '../../i18n/server';
import LocationSearch, { type SearchedLocation } from './LocationSearch';
import MapLegend from './MapLegend';

const DESKTOP_TOP_CARD_CLASS = 'w-[300px]';
const DESKTOP_LOCATION_SEARCH_INPUT_CLASS =
  'px-2 py-2 text-sm w-full border-none outline-none bg-transparent text-warm-700 dark:text-warm-200 placeholder-warm-400 dark:placeholder-warm-500';

interface MapTopCardsProps {
  layoutClass: string;
  showLocationSearch: boolean;
  showLegend: boolean;
  /**
   * Space (px) to keep clear on the right of the overlay so the cards don't
   * slide under sibling controls anchored there (e.g. the mobile action
   * buttons). The expanded location search shrinks to fit the remaining width.
   */
  rightInset?: number;
  onFlyTo: (lat: number, lng: number, zoom: number, options?: MapFlyToOptions) => void;
  onLocationSearched?: (location: SearchedLocation | null) => void;
  onCurrentLocationFound?: (lat: number, lng: number) => void;
  onLocationSearchMouseEnter: () => void;
  getViewportCenter: () => { lat: number; lng: number } | null;
  viewFeature: string | null;
  colorRange: [number, number] | null;
  viewSource: 'drag' | 'eye' | null;
  onCancelPin: () => void;
  onResetPreviewScale?: () => void;
  canResetPreviewScale: boolean;
  colorFeatureMeta: FeatureMeta | null;
  usePostcodeView: boolean;
  countRange: { min: number; max: number };
  postcodeCountRange: { min: number; max: number };
  densityLabel: string;
  totalCount?: number;
  theme: 'light' | 'dark';
}

/** Desktop top-card overlay area: the location search box and the map legend. */
export const MapTopCards = memo(function MapTopCards({
  layoutClass,
  showLocationSearch,
  showLegend,
  rightInset = 0,
  onFlyTo,
  onLocationSearched,
  onCurrentLocationFound,
  onLocationSearchMouseEnter,
  getViewportCenter,
  viewFeature,
  colorRange,
  viewSource,
  onCancelPin,
  onResetPreviewScale,
  canResetPreviewScale,
  colorFeatureMeta,
  usePostcodeView,
  countRange,
  postcodeCountRange,
  densityLabel,
  totalCount,
  theme,
}: MapTopCardsProps) {
  const { t } = useTranslation();
  const modes = useTranslatedModes();

  return (
    <div
      className={`absolute top-3 left-3 right-3 z-20 flex gap-2 pointer-events-none ${layoutClass}`}
      style={rightInset ? { paddingRight: rightInset } : undefined}
    >
      {showLocationSearch && (
        <LocationSearch
          onFlyTo={onFlyTo}
          onLocationSearched={onLocationSearched}
          onCurrentLocationFound={onCurrentLocationFound}
          onMouseEnter={onLocationSearchMouseEnter}
          getViewportCenter={getViewportCenter}
          className={DESKTOP_TOP_CARD_CLASS}
          inputClassName={DESKTOP_LOCATION_SEARCH_INPUT_CLASS}
        />
      )}
      {showLegend &&
        (viewFeature && colorRange ? (
          viewFeature.startsWith('tt_') ? (
            <MapLegend
              featureLabel={t('travel.travelTime', {
                mode: modes.label(
                  viewFeature.split('_')[1] as 'car' | 'bicycle' | 'walking' | 'transit'
                ),
              })}
              range={colorRange}
              showCancel={viewSource === 'eye'}
              onCancel={onCancelPin}
              onResetScale={viewSource === 'eye' ? onResetPreviewScale : undefined}
              resetScaleDisabled={!canResetPreviewScale}
              mode="feature"
              theme={theme}
              suffix=" min"
              className={DESKTOP_TOP_CARD_CLASS}
            />
          ) : colorFeatureMeta ? (
            <MapLegend
              featureLabel={
                viewSource === 'eye'
                  ? t('mapLegend.previewing', { name: ts(colorFeatureMeta.name) })
                  : ts(colorFeatureMeta.name)
              }
              range={colorRange}
              showCancel={viewSource === 'eye'}
              onCancel={onCancelPin}
              onResetScale={viewSource === 'eye' ? onResetPreviewScale : undefined}
              resetScaleDisabled={!canResetPreviewScale}
              mode="feature"
              enumValues={colorFeatureMeta.type === 'enum' ? colorFeatureMeta.values : undefined}
              featureName={colorFeatureMeta.name}
              theme={theme}
              suffix={colorFeatureMeta.suffix}
              raw={colorFeatureMeta.raw}
              className={DESKTOP_TOP_CARD_CLASS}
            />
          ) : null
        ) : (
          <MapLegend
            featureLabel={densityLabel}
            range={
              usePostcodeView
                ? [postcodeCountRange.min, postcodeCountRange.max]
                : [countRange.min, countRange.max]
            }
            totalCount={totalCount}
            showCancel={false}
            onCancel={onCancelPin}
            mode="density"
            theme={theme}
            className={DESKTOP_TOP_CARD_CLASS}
          />
        ))}
    </div>
  );
});
