import { useState, useRef, useEffect, useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { createPortal } from 'react-dom';
import type { Destination } from '../../hooks/useTravelDestinations';
import { useDropdownPosition } from '../../hooks/useDropdownPosition';
import { MapPinIcon } from './icons/MapPinIcon';
import { ChevronIcon } from './icons/ChevronIcon';
import { CloseIcon } from './icons/CloseIcon';

interface DestinationDropdownProps {
  destinations: Destination[];
  loading: boolean;
  onSelect: (slug: string, label: string, lat: number, lon: number) => void;
  onClear?: () => void;
  value?: string;
  placeholder?: string;
}

export function DestinationDropdown({
  destinations,
  loading,
  onSelect,
  onClear,
  value,
  placeholder,
}: DestinationDropdownProps) {
  const { t } = useTranslation();
  const [open, setOpen] = useState(false);
  const [filter, setFilter] = useState('');
  const [activeIndex, setActiveIndex] = useState(-1);
  const containerRef = useRef<HTMLDivElement>(null);
  const dropdownRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);
  const listRef = useRef<HTMLDivElement>(null);
  const pos = useDropdownPosition(containerRef, open);

  const filtered = useMemo(() => {
    if (!filter) return destinations;
    const lower = filter.toLowerCase();
    return destinations.filter(
      (d) => d.name.toLowerCase().includes(lower) || d.city?.toLowerCase().includes(lower)
    );
  }, [destinations, filter]);

  // Close on outside click
  useEffect(() => {
    if (!open) return;
    const handler = (e: MouseEvent) => {
      if (
        containerRef.current &&
        !containerRef.current.contains(e.target as Node) &&
        !dropdownRef.current?.contains(e.target as Node)
      ) {
        setOpen(false);
        setFilter('');
      }
    };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, [open]);

  // Scroll active item into view
  useEffect(() => {
    if (activeIndex < 0 || !listRef.current) return;
    const item = listRef.current.children[activeIndex] as HTMLElement;
    item?.scrollIntoView({ block: 'nearest' });
  }, [activeIndex]);

  const handleSelect = useCallback(
    (dest: Destination) => {
      onSelect(dest.slug, dest.name, dest.lat, dest.lon);
      setOpen(false);
      setFilter('');
      setActiveIndex(-1);
    },
    [onSelect]
  );

  const handleKeyDown = useCallback(
    (e: React.KeyboardEvent) => {
      if (e.key === 'ArrowDown') {
        e.preventDefault();
        setActiveIndex((prev) => (prev < filtered.length - 1 ? prev + 1 : prev));
      } else if (e.key === 'ArrowUp') {
        e.preventDefault();
        setActiveIndex((prev) => (prev > 0 ? prev - 1 : -1));
      } else if (e.key === 'Enter') {
        e.preventDefault();
        if (activeIndex >= 0 && activeIndex < filtered.length) {
          handleSelect(filtered[activeIndex]);
        }
      } else if (e.key === 'Escape') {
        setOpen(false);
        setFilter('');
      }
    },
    [filtered, activeIndex, handleSelect]
  );

  const handleOpen = useCallback(() => {
    setOpen(true);
    setActiveIndex(-1);
    // Focus input after opening
    requestAnimationFrame(() => inputRef.current?.focus());
  }, []);

  const dropdown = open && (
    <div
      ref={dropdownRef}
      className="bg-white dark:bg-warm-800 rounded shadow-lg border border-warm-200 dark:border-warm-700 overflow-hidden"
      style={
        pos
          ? {
              position: 'fixed',
              top: pos.top,
              left: pos.left,
              width: pos.width,
              zIndex: 50,
            }
          : undefined
      }
    >
      {/* Filter input */}
      <div className="p-1.5 border-b border-warm-100 dark:border-warm-700">
        <input
          ref={inputRef}
          type="text"
          value={filter}
          onChange={(e) => {
            setFilter(e.target.value);
            setActiveIndex(-1);
          }}
          onKeyDown={handleKeyDown}
          placeholder={t('travel.typeToFilter')}
          className="w-full px-2 py-1 text-xs rounded border border-warm-200 dark:border-warm-600 bg-warm-50 dark:bg-warm-900 text-navy-950 dark:text-warm-200 placeholder-warm-400 dark:placeholder-warm-500 outline-none focus:ring-1 focus:ring-teal-400"
        />
      </div>

      {/* Results list */}
      <div ref={listRef} className="max-h-48 overflow-y-auto">
        {filtered.length === 0 ? (
          <div className="px-2 py-2 text-xs text-warm-400 dark:text-warm-500 text-center">
            {loading ? t('common.loading') : t('travel.noDestinations')}
          </div>
        ) : (
          filtered.map((dest, idx) => (
            <button
              key={dest.slug}
              type="button"
              className={`w-full text-left flex items-center cursor-pointer px-2 py-1.5 gap-1.5 text-xs ${
                idx === activeIndex
                  ? 'bg-teal-50 dark:bg-teal-900/30'
                  : 'hover:bg-warm-50 dark:hover:bg-warm-700'
              }`}
              onMouseEnter={() => setActiveIndex(idx)}
              onMouseDown={(e) => {
                e.preventDefault();
                handleSelect(dest);
              }}
            >
              <MapPinIcon className="w-3 h-3 text-warm-400 dark:text-warm-500 shrink-0" />
              <span className="text-warm-700 dark:text-warm-200 truncate">
                {dest.name}
                {dest.city && (
                  <span className="text-warm-400 dark:text-warm-500"> ({dest.city})</span>
                )}
              </span>
            </button>
          ))
        )}
      </div>
    </div>
  );

  return (
    <div ref={containerRef} className="relative">
      <div
        className={`w-full flex items-center gap-1.5 px-2 py-1 text-xs rounded border ${value ? 'border-warm-200 dark:border-warm-700 bg-warm-50 dark:bg-warm-800' : 'border-warm-200 dark:border-warm-600 bg-white dark:bg-warm-800 hover:border-warm-300 dark:hover:border-warm-500'}`}
      >
        <button
          type="button"
          onClick={handleOpen}
          className="flex items-center gap-1.5 flex-1 min-w-0 outline-none"
        >
          {loading ? (
            <div className="w-3 h-3 border-2 border-warm-300 dark:border-warm-600 border-t-teal-500 rounded-full animate-spin shrink-0" />
          ) : (
            <MapPinIcon
              className={`w-3 h-3 shrink-0 ${value ? 'text-red-500' : 'text-warm-400 dark:text-warm-500'}`}
            />
          )}
          <span
            className={`flex-1 text-left truncate ${value ? 'text-navy-950 dark:text-warm-200' : 'text-warm-400 dark:text-warm-500'}`}
          >
            {value || placeholder || t('travel.selectDestination')}
          </span>
        </button>
        {value && onClear ? (
          <button
            type="button"
            onClick={onClear}
            className="text-warm-400 hover:text-warm-700 dark:hover:text-warm-300 shrink-0"
            title={t('travel.clearDestination')}
          >
            <CloseIcon className="w-3 h-3" />
          </button>
        ) : (
          <ChevronIcon
            direction={open ? 'up' : 'down'}
            className="w-3 h-3 shrink-0 text-warm-400 dark:text-warm-500"
          />
        )}
      </div>

      {open && createPortal(dropdown, document.body)}
    </div>
  );
}
