import { useEffect, useId, useMemo, useState } from "react";
import { useCustomerListQuery } from "../../hooks";
import { CustomerFormData, CustomerSummary, defaultCustomerFormData } from "../../schemas";
import { CustomerCard } from "./customer-card";
import { CustomerCreateModal } from './customer-create-modal';
import { CustomerEmptyCard } from "./customer-empty-card";
import { CustomerSearchDialog } from "./customer-search-dialog";
import { CustomerViewDialog } from './customer-view-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;
}


type CustomerModalSelectorProps = {
  value?: string;
  onValueChange?: (id: string) => void;
  disabled?: boolean; // Solo lectura total (sin botones ni selección)
  readOnly?: boolean; // Ver ficha, pero no cambiar/crear
  initialCustomer?: CustomerSummary;
  className?: string;
}

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

  const dialogId = useId();

  const [showSearch, setShowSearch] = useState(false);
  const [showNewForm, setShowNewForm] = useState(false);
  const [showView, setShowView] = useState(false);

  const [searchQuery, setSearchQuery] = useState("");
  const debouncedQuery = useDebouncedValue(searchQuery, 300);

  // Cliente seleccionado + creados localmente (optimista)
  const [selected, setSelected] = useState<CustomerSummary | null>(initialCustomer ?? null);
  const [localCreated, setLocalCreated] = useState<CustomerSummary[]>([]);

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

  const criteria = useMemo(
    () => ({
      q: debouncedQuery || "",
      pageSize: 5,
      orderBy: "updated_at" as const,
      order: "asc" as const,
    }),
    [debouncedQuery]
  );

  // Consulta solo cuando el diálogo de búsqueda está abierto
  const {
    data: remoteCustomersPage,
    isLoading,
    isError,
    error,
  } = useCustomerListQuery(
    {
      enabled: showSearch, // <- evita llamadas innecesarias
      criteria
    }
  );

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


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


  // Crear cliente (optimista) mapeando desde CustomerDraft -> CustomerSummary
  const handleCreate = () => {
    if (!newClient.name || !newClient.email_primary) return;

    const newCustomer: CustomerSummary = defaultCustomerFormData as CustomerSummary;

    setLocalCreated((prev) => [newCustomer, ...prev]);
    onValueChange?.(newCustomer.id); // RHF es el source of truth
    setShowNewForm(false);
    setShowSearch(false);
  };

  // Handlers de tarjeta según modo
  const canChange = !disabled && !readOnly;
  const canCreate = !disabled && !readOnly;
  const canView = !!selected && !disabled;

  return (
    <>
      <div>
        {selected ? (
          <CustomerCard
            className={className}
            customer={selected}
            onViewCustomer={canView ? () => setShowView(true) : undefined}
            onChangeCustomer={canChange ? () => setShowSearch(true) : undefined}
            onAddNewCustomer={canCreate ? () => setShowNewForm(true) : undefined}
          />
        ) : (
          <CustomerEmptyCard
            className={className}
            onClick={!disabled && !readOnly ? () => setShowSearch(true) : undefined}
            onKeyDown={
              !disabled && !readOnly
                ? (e) => {
                  if (e.key === "Enter" || e.key === " ") setShowSearch(true);
                }
                : undefined
            }
            aria-haspopup="dialog"
            aria-controls={dialogId}
            aria-disabled={disabled || readOnly}
          />
        )}
      </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((prev) => ({ ...prev, name: name ?? "" }));
          setShowNewForm(true);
        }}
        isLoading={isLoading}
        isError={isError}
        errorMessage={isError ? ((error as Error)?.message ?? "Error al cargar clientes") : undefined}
      />

      <CustomerViewDialog
        customerId={selected?.id ?? null}
        open={showView}
        onOpenChange={setShowView}
      />

      {/* Diálogo de alta rápida */}
      <CustomerCreateModal
        open={showNewForm}
        onOpenChange={setShowNewForm}
        client={newClient}
        onChange={setNewClient}
        onSubmit={handleCreate}
      />
    </>
  );
};