"use client";

// Drapeaux SVG depuis le CDN country-flag-icons (même source que le champ téléphone react-phone-number-input).
import { useEffect, useMemo, useRef, useState } from 'react';
import { Check, ChevronDown, Search } from 'lucide-react';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { cn } from '@/lib/utils';
import { countryOptions } from '@/lib/countries';
import { useGeoCountry } from '@/lib/useGeoCountry';
import { inputClass, type FormTheme } from './Field';

const flagUrl = (iso: string) =>
  `https://purecatamphetamine.github.io/country-flag-icons/3x2/${iso}.svg`;

type Props = {
  id?: string;
  value: string | undefined; // nom EN (propriété HubSpot `country`) ou ''
  onChange: (value: string) => void;
  theme?: FormTheme;
};

export const CountrySelect = ({ id, value, onChange, theme = 'light' }: Props) => {
  const dark = theme === 'dark';
  const [open, setOpen] = useState(false);
  const [query, setQuery] = useState('');
  const geoIso = useGeoCountry('FR');

  const selected = useMemo(() => countryOptions.find((c) => c.value === value), [value]);

  // Défaut : pré-remplir avec le pays déduit de l'IP (fallback FR) si le champ est vide.
  const didDefault = useRef(false);
  useEffect(() => {
    if (didDefault.current || value) return;
    const match = countryOptions.find((c) => c.iso === geoIso);
    if (match) {
      didDefault.current = true;
      onChange(match.value);
    }
  }, [geoIso, value, onChange]);

  const filtered = useMemo(() => {
    const q = query.trim().toLowerCase();
    if (!q) return countryOptions;
    return countryOptions.filter(
      (c) => c.label.toLowerCase().includes(q) || c.iso.toLowerCase().includes(q),
    );
  }, [query]);

  return (
    <Popover
      open={open}
      onOpenChange={(o) => {
        setOpen(o);
        if (!o) setQuery('');
      }}
    >
      <PopoverTrigger asChild>
        <button type="button" id={id} className={`${inputClass(theme)} flex items-center gap-2 text-left`}>
          {selected ? (
            <>
              <img src={flagUrl(selected.iso)} alt="" className="w-5 h-auto rounded-sm shrink-0" />
              <span className={cn('flex-1 truncate', dark ? 'text-white' : 'text-foreground')}>{selected.label}</span>
            </>
          ) : (
            <span className={cn('flex-1 truncate', dark ? 'text-white/40' : 'text-foreground/30')}>Veuillez sélectionner</span>
          )}
          <ChevronDown className={cn('w-5 h-5 shrink-0', dark ? 'text-white/50' : 'text-foreground/40')} strokeWidth={2} />
        </button>
      </PopoverTrigger>
      <PopoverContent
        align="start"
        className={cn(
          'w-[--radix-popover-trigger-width] p-0 overflow-hidden',
          dark && 'bg-[#0b1a2b] border-white/10 text-white',
        )}
      >
        <div className={cn('flex items-center gap-2 border-b px-3 py-2', dark && 'border-white/10')}>
          <Search className={cn('w-4 h-4 shrink-0', dark ? 'text-white/40' : 'text-foreground/40')} />
          <input
            autoFocus
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            placeholder="Rechercher un pays…"
            className={cn(
              'flex-1 bg-transparent outline-none text-sm',
              dark ? 'text-white placeholder:text-white/40' : 'text-foreground placeholder:text-foreground/40',
            )}
          />
        </div>
        <ul className="max-h-64 overflow-y-auto py-1">
          {filtered.length === 0 && (
            <li className={cn('px-3 py-2 text-sm', dark ? 'text-white/40' : 'text-foreground/40')}>Aucun résultat</li>
          )}
          {filtered.map((c) => {
            const active = c.value === value;
            return (
              <li key={c.iso}>
                <button
                  type="button"
                  onClick={() => {
                    onChange(c.value);
                    setOpen(false);
                    setQuery('');
                  }}
                  className={cn(
                    'w-full flex items-center gap-2 px-3 py-2 text-sm text-left transition-colors',
                    dark ? 'hover:bg-white/5' : 'hover:bg-foreground/5',
                    active && (dark ? 'bg-white/10' : 'bg-primary/5'),
                  )}
                >
                  <img src={flagUrl(c.iso)} alt="" className="w-5 h-auto rounded-sm shrink-0" />
                  <span className={cn('flex-1 truncate', dark ? 'text-white' : 'text-foreground')}>{c.label}</span>
                  {active && <Check className="w-4 h-4 text-primary shrink-0" strokeWidth={2.5} />}
                </button>
              </li>
            );
          })}
        </ul>
      </PopoverContent>
    </Popover>
  );
};
