"use client";

import * as React from "react";

import { ChevronsUpDown, Loader2, Search } from "lucide-react";

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { FRONTEND_ROUTES } from "@/config/frontend-routes";
import { requestDashboardApi } from "@/lib/dashboard-api-client";
import { cn } from "@/lib/utils";

import type { OrderCustomerOption } from "../schema";

const SEARCH_DEBOUNCE_MS = 300;

type CustomerPickerProps = {
  id?: string;
  value: OrderCustomerOption | null;
  onSelect: (customer: OrderCustomerOption) => void;
  invalid?: boolean;
};

/** Searchable customer select backed by the real customer table. */
export function CustomerPicker({ id, value, onSelect, invalid }: CustomerPickerProps) {
  const [open, setOpen] = React.useState(false);
  const [term, setTerm] = React.useState("");
  const [results, setResults] = React.useState<OrderCustomerOption[]>([]);
  const [isLoading, setIsLoading] = React.useState(false);
  const [error, setError] = React.useState<string | null>(null);

  React.useEffect(() => {
    if (!open) return;

    const controller = new AbortController();
    const timer = window.setTimeout(async () => {
      setIsLoading(true);
      setError(null);
      try {
        const data = await requestDashboardApi<{ items?: OrderCustomerOption[] }>({
          url: FRONTEND_ROUTES.plansOrders.orders.customers,
          method: "POST",
          body: { term: term.trim() },
          signal: controller.signal,
          fallbackError: "Customers could not be loaded.",
          validate: (payload) => Array.isArray(payload.items),
        });
        setResults(data.items ?? []);
      } catch (searchError) {
        if (controller.signal.aborted) return;
        setResults([]);
        setError(searchError instanceof Error ? searchError.message : "Customers could not be loaded.");
      } finally {
        if (!controller.signal.aborted) setIsLoading(false);
      }
    }, SEARCH_DEBOUNCE_MS);

    return () => {
      window.clearTimeout(timer);
      controller.abort();
    };
  }, [open, term]);

  return (
    <Popover open={open} onOpenChange={setOpen}>
      <PopoverTrigger asChild>
        <Button
          id={id}
          type="button"
          variant="outline"
          role="combobox"
          aria-expanded={open}
          aria-invalid={invalid}
          className={cn(
            "h-9 w-full justify-between font-normal",
            !value && "text-muted-foreground",
            invalid && "border-destructive",
          )}
        >
          <span className="truncate">{value ? value.name : "Search customer…"}</span>
          <ChevronsUpDown className="size-4 shrink-0 opacity-50" />
        </Button>
      </PopoverTrigger>
      <PopoverContent align="start" className="w-[var(--radix-popover-trigger-width,22rem)] min-w-80 p-2">
        <div className="relative">
          <Search className="pointer-events-none absolute top-1/2 left-2.5 size-4 -translate-y-1/2 text-muted-foreground" />
          <Input
            autoFocus
            value={term}
            onChange={(event) => setTerm(event.target.value)}
            placeholder="Name, company, email or ID"
            className="h-9 pl-8"
          />
        </div>
        <ul className="mt-2 max-h-64 overflow-y-auto" role="listbox">
          {isLoading ? (
            <li className="flex items-center gap-2 px-2 py-3 text-muted-foreground text-xs">
              <Loader2 className="size-3.5 animate-spin" /> Searching…
            </li>
          ) : error ? (
            <li className="px-2 py-3 text-destructive text-xs">{error}</li>
          ) : results.length === 0 ? (
            <li className="px-2 py-3 text-muted-foreground text-xs">No customers found.</li>
          ) : (
            results.map((customer) => (
              <li key={customer.id}>
                <button
                  type="button"
                  role="option"
                  aria-selected={value?.id === customer.id}
                  className="flex w-full flex-col items-start rounded-md px-2 py-1.5 text-left hover:bg-muted"
                  onClick={() => {
                    onSelect(customer);
                    setOpen(false);
                  }}
                >
                  <span className="text-sm font-medium">{customer.name}</span>
                  <span className="text-muted-foreground text-xs">
                    {[customer.company, customer.email].filter(Boolean).join(" · ")}
                  </span>
                </button>
              </li>
            ))
          )}
        </ul>
      </PopoverContent>
    </Popover>
  );
}
