import { useEffect, useMemo, useState } from "react";
import { useCustomersSearchQuery } from "../../hooks";
import { CustomerSummary, defaultCustomerFormData } from "../../schemas";
import { CreateCustomerFormDialog } from "./create-customer-form-dialog";
import { CustomerCard } from "./customer-card";
import { CustomerEmptyCard } from "./customer-empty-card";
import { CustomerSearchDialog } from "./customer-search-dialog";

// Debounce pequeño y tipado
function useDebouncedValue<T>(value: T, delay = 300) {
  const [debounced, setDebounced] = useState<T>(value);
  useEffect(() => {
    const id = setTimeout(() => setDebounced(value), delay);
    return () => clearTimeout(id);
  }, [value, delay]);
  return debounced;
}

interface CustomerModalSelectorProps {
  value?: string;
  onValueChange?: (id: string) => void;
  disabled?: boolean;
  readOnly?: boolean;
  initialCustomer?: CustomerSummary;
  className?: string;
}

export const CustomerModalSelector = ({
  value,
  onValueChange,
  disabled = false,
  readOnly = false,
  initialCustomer,
  className,
}: CustomerModalSelectorProps) => {

  const [showSearch, setShowSearch] = useState(false);
  const [showForm, setShowForm] = useState(false);
  const [searchQuery, setSearchQuery] = useState("");
  const debouncedQuery = useDebouncedValue(searchQuery, 300);

  // Cliente seleccionado y creación local optimista
  const [selected, setSelected] = useState<CustomerSummary | null>(initialCustomer ?? null);

  const [newClient, setNewClient] =
    useState<Omit<CustomerSummary, "id" | "status" | "company_id">>(defaultCustomerFormData);

  const [localCreated, setLocalCreated] = useState<CustomerSummary[]>([]);

  const {
    data: remoteCustomers = [],
    isLoading,
    isError,
    error,
  } = useCustomersSearchQuery({
    q: debouncedQuery,
    pageSize: 5,
    orderBy: "updated_at",
    order: "asc",
  });

  // Combinar locales optimistas + remotos
  const customers: CustomerSummary[] = useMemo(() => {
    const byId = new Map<string, CustomerSummary>();
    [...localCreated, ...remoteCustomers].forEach((c) => byId.set(c.id, c as CustomerSummary));
    return Array.from(byId.values());
  }, [localCreated, remoteCustomers]);

  // Sync con `value`
  useEffect(() => {
    const found = customers.find((c) => c.id === value) ?? initialCustomer;
    setSelected(found);
  }, [value, customers]);

  const handleCreate = () => {
    if (!newClient.name || !newClient.email) return;
    const newCustomer: CustomerSummary = {
      id: crypto.randomUUID?.() ?? Date.now().toString(),
      ...newClient,
    };
    setLocalCreated((prev) => [newCustomer, ...prev]);
    onValueChange?.(newCustomer.id); // <- ahora el "source of truth" es React Hook Form
    setShowForm(false);
    setShowSearch(false);
  };

  console.log(selected);

  return (
    <>
      <div>
        {selected ? (
          <CustomerCard
            className={className}
            customer={selected}
            onChangeCustomer={() => setShowSearch(true)}
            onViewCustomer={() => null}
            onAddNewCustomer={() => null}
          />
        ) : (
          <CustomerEmptyCard
            className={className}
            onClick={() => setShowSearch(true)}
            onKeyDown={(e) => (e.key === "Enter" || e.key === " ") && setShowSearch(true)}
          />
        )}
      </div>

      <CustomerSearchDialog
        open={showSearch}
        onOpenChange={setShowSearch}
        searchQuery={searchQuery}
        onSearchQueryChange={setSearchQuery}
        customers={customers}
        selectedClient={selected}
        onSelectClient={(c) => {
          setSelected(c);
          onValueChange?.(c.id);
          setShowSearch(false);
        }}
        onCreateClient={(name) => {
          setNewClient({ name: name ?? "", email: "" });
          setShowForm(true);
        }}
        isLoading={isLoading}
        isError={isError}
        errorMessage={
          isError ? ((error as Error)?.message ?? "Error al cargar clientes") : undefined
        }
      />

      <CreateCustomerFormDialog
        open={showForm}
        onOpenChange={setShowForm}
        client={newClient}
        onChange={setNewClient}
        onSubmit={handleCreate}
      />
    </>
  );
};
