import { useQuery } from "@tanstack/react-query";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Label } from "@/components/ui/label";
import { Users } from "lucide-react";

export interface DelegateRecord {
  id: string;
  first_name: string;
  last_name: string;
  email: string | null;
  phone: string | null;
}

export interface DelegatePickFields {
  first_name: string;
  last_name: string;
  email: string;
  phone: string;
}

interface Props {
  companyId: string | null | undefined;
  /** Called when a delegate is chosen. The empty value means "manual entry". */
  onPick: (delegate: DelegatePickFields) => void;
  /** Optional list of emails to hide (e.g. delegates already added to this booking). */
  excludeEmails?: string[];
  /** Compact spacing variant for the cart's tighter rows. */
  size?: "sm" | "md";
}

/**
 * Dropdown that shows a company's delegates. Picking one fires `onPick` with
 * the delegate's name/email/phone so the calling component can pre-fill its
 * inputs. Hidden entirely if there's no companyId or the company has no
 * delegates yet.
 */
const DelegatePicker = ({ companyId, onPick, excludeEmails = [], size = "md" }: Props) => {
  const { data: delegates = [] } = useQuery({
    queryKey: ["company-delegates-picker", companyId],
    enabled: !!companyId,
    queryFn: async (): Promise<DelegateRecord[]> => {
      const res = await fetch(`/api/delegates?company_id=${encodeURIComponent(companyId!)}`);
      if (!res.ok) return [];
      const data = await res.json();
      return Array.isArray(data) ? data : (data?.data ?? []);
    },
    staleTime: 30_000,
  });

  if (!companyId) return null;

  const excludeSet = new Set(
    excludeEmails.map((e) => (e || "").trim().toLowerCase()).filter(Boolean),
  );
  const visible = delegates.filter((d) => {
    const e = (d.email || "").trim().toLowerCase();
    return !e || !excludeSet.has(e);
  });

  if (visible.length === 0) return null;

  const handleChange = (value: string) => {
    if (!value || value === "__manual__") {
      onPick({ first_name: "", last_name: "", email: "", phone: "" });
      return;
    }
    const d = delegates.find((x) => x.id === value);
    if (!d) return;
    onPick({
      first_name: d.first_name || "",
      last_name: d.last_name || "",
      email: d.email || "",
      phone: d.phone || "",
    });
  };

  const isSm = size === "sm";

  return (
    <div className={isSm ? "space-y-1" : "space-y-1.5"}>
      <Label className={isSm ? "text-[10px]" : "text-xs"}>
        <Users className="inline h-3 w-3 mr-1" />
        Pre-fill from existing delegates
      </Label>
      <Select onValueChange={handleChange}>
        <SelectTrigger className={isSm ? "h-8 text-xs" : "h-9 text-sm"}>
          <SelectValue placeholder={`Choose from ${visible.length} delegate${visible.length === 1 ? "" : "s"}…`} />
        </SelectTrigger>
        <SelectContent>
          <SelectItem value="__manual__">— Manual entry —</SelectItem>
          {visible.map((d) => (
            <SelectItem key={d.id} value={d.id}>
              <span className="font-medium">{d.first_name} {d.last_name}</span>
              {d.email && <span className="text-muted-foreground ml-2 text-xs">{d.email}</span>}
            </SelectItem>
          ))}
        </SelectContent>
      </Select>
    </div>
  );
};

export default DelegatePicker;
