import { useMemo, useState } from 'react';
import type { IsoCountryOption } from '../../lib/countries/iso';
import { flagIconClass } from '../../lib/countries/flag';

type Props = {
  options: IsoCountryOption[];
  excludeCodes: string[];
  initialCode?: string;
  labels: {
    search: string;
    select: string;
    alreadyAdded: string;
    selected: string;
  };
};

export default function CountryPicker({ options, excludeCodes, initialCode = '', labels }: Props) {
  const [query, setQuery] = useState('');
  const [selectedCode, setSelectedCode] = useState(initialCode);
  const [open, setOpen] = useState(false);

  const excludeSet = useMemo(() => new Set(excludeCodes.map((c) => c.toUpperCase())), [excludeCodes]);

  const filtered = useMemo(() => {
    const q = query.trim().toLowerCase();
    if (!q) return options;
    return options.filter(
      (o) =>
        o.code.toLowerCase().includes(q) ||
        o.nameEn.toLowerCase().includes(q) ||
        o.nameAr.includes(q),
    );
  }, [options, query]);

  const selected = options.find((o) => o.code === selectedCode);

  return (
    <div className="space-y-3">
      <input type="hidden" name="isoCode" value={selectedCode} required />

      <label className="form-control w-full">
        <span className="label-text mb-1 font-medium">{labels.select}</span>
        <input
          type="search"
          value={query}
          onChange={(e) => {
            setQuery(e.target.value);
            setOpen(true);
          }}
          onFocus={() => setOpen(true)}
          placeholder={labels.search}
          className="input input-bordered w-full"
          autoComplete="off"
        />
      </label>

      {open && (
        <div className="max-h-64 overflow-y-auto rounded-box border border-base-300 bg-base-100 shadow-sm">
          {filtered.length === 0 ? (
            <p className="p-4 text-sm text-base-content/60">{labels.search}</p>
          ) : (
            <ul className="divide-y divide-base-300/60">
              {filtered.map((option) => {
                const taken = excludeSet.has(option.code);
                const isSelected = selectedCode === option.code;

                return (
                  <li key={option.code}>
                    <button
                      type="button"
                      disabled={taken}
                      onClick={() => {
                        if (taken) return;
                        setSelectedCode(option.code);
                        setQuery('');
                        setOpen(false);
                      }}
                      className={`flex w-full items-center gap-3 px-4 py-3 text-start transition-colors ${
                        taken
                          ? 'cursor-not-allowed opacity-50'
                          : isSelected
                            ? 'bg-primary/10'
                            : 'hover:bg-base-200'
                      }`}
                    >
                      <span className={`${flagIconClass(option.code)} text-2xl`} aria-hidden="true" />
                      <span className="min-w-0 flex-1">
                        <span className="block font-medium">{option.nameEn}</span>
                        <span className="block text-sm text-base-content/60">{option.nameAr}</span>
                      </span>
                      {taken && (
                        <span className="badge badge-ghost badge-sm shrink-0">{labels.alreadyAdded}</span>
                      )}
                    </button>
                  </li>
                );
              })}
            </ul>
          )}
        </div>
      )}

      {selected && (
        <div className="flex items-center gap-3 rounded-box border border-base-300 bg-base-200/50 p-4">
          <span className={`${flagIconClass(selected.code)} text-3xl`} aria-hidden="true" />
          <div>
            <p className="text-sm text-base-content/60">{labels.selected}</p>
            <p className="font-bold">{selected.nameEn}</p>
            <p className="text-sm text-base-content/70">{selected.nameAr}</p>
          </div>
        </div>
      )}
    </div>
  );
}
