import {
  Badge,
  Button,
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@repo/shadcn-ui/components";
import { cn } from "@repo/shadcn-ui/lib/utils";
import {
  Check,
  CreditCardIcon,
  MailIcon,
  SmartphoneIcon,
  User,
  UserIcon,
  UserPlusIcon,
} from "lucide-react";
import { CustomerSummary } from "../../schemas";

interface CustomerSearchDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  searchQuery: string;
  onSearchQueryChange: (q: string) => void;
  customers: CustomerSummary[];
  selectedClient: CustomerSummary | null;
  onSelectClient: (c: CustomerSummary) => void;
  onCreateClient: (name?: string) => void;
  isLoading?: boolean;
  isError?: boolean;
  errorMessage?: string;
}

export const CustomerSearchDialog = ({
  open,
  onOpenChange,
  searchQuery,
  onSearchQueryChange,
  customers,
  selectedClient,
  onSelectClient,
  onCreateClient,
  isLoading,
  isError,
  errorMessage,
}: CustomerSearchDialogProps) => {
  const isEmpty = !isLoading && !isError && customers && customers.length === 0;

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className='sm:max-w-2xl bg-card border-border p-0'>
        <DialogHeader className='px-6 pt-6 pb-4'>
          <DialogTitle className='flex items-center justify-between'>
            <span className='flex items-center gap-2'>
              <User className='size-5' />
              Seleccionar Cliente
            </span>
          </DialogTitle>
          <DialogDescription>Busca un cliente existente o crea uno nuevo.</DialogDescription>
        </DialogHeader>

        <div className='px-6 pb-3'>
          <Command className='border rounded-lg' shouldFilter={false}>
            <CommandInput
              placeholder='Buscar cliente...'
              value={searchQuery}
              onValueChange={onSearchQueryChange}
            />

            <CommandList className='max-h-[600px]'>
              <CommandEmpty>
                <div className='flex flex-col items-center gap-2 py-6 text-sm'>
                  <User className='size-8 text-muted-foreground/50' />
                  {isLoading && <p>Cargando…</p>}
                  {isError && <p className='text-destructive'>{errorMessage}</p>}
                  {!isLoading && !isError && (
                    <>
                      <p>No se encontraron clientes</p>
                      {searchQuery && (
                        <Button
                          onClick={() => onCreateClient(searchQuery)}
                          className='cursor-pointer'
                        >
                          <UserPlusIcon className='mr-2 size-4' />
                          Crear cliente "{searchQuery}"
                        </Button>
                      )}
                    </>
                  )}
                </div>
              </CommandEmpty>

              <CommandGroup>
                {customers.map((customer) => {
                  return (
                    <CommandItem
                      key={customer.id}
                      value={customer.id}
                      onSelect={() => onSelectClient(customer)}
                      className='flex items-center gap-x-4 py-5 cursor-pointer'
                    >
                      <div className='flex size-12  items-center justify-center rounded-full bg-primary/10'>
                        <UserIcon className='size-8 stroke-1 text-primary' />
                      </div>
                      <div className='flex-1 space-y-1 min-w-0'>
                        <div className='flex items-center gap-2'>
                          <span className='text-sm font-semibold'>{customer.name}</span>
                          {customer.trade_name && (
                            <Badge variant='secondary' className='text-sm'>
                              {customer.trade_name}
                            </Badge>
                          )}
                        </div>
                        <div className='flex items-center gap-6 text-sm font-medium text-muted-foreground'>
                          {customer.tin && (
                            <div className='flex items-center gap-2 text-sm text-muted-foreground'>
                              <CreditCardIcon className='h-4 w-4 shrink-0' />
                              <span className='font-medium'>{customer.tin}</span>
                            </div>
                          )}
                          {customer.email_primary && (
                            <span className='flex items-center gap-1'>
                              <MailIcon className='size-4' /> {customer.email_primary}
                            </span>
                          )}
                          {customer.mobile_primary && (
                            <span className='flex items-center gap-1'>
                              <SmartphoneIcon className='size-4' /> {customer.mobile_primary}
                            </span>
                          )}
                        </div>
                      </div>
                      <Check
                        className={cn(
                          "ml-auto size-4",
                          selectedClient?.id === customer.id ? "opacity-100" : "opacity-0"
                        )}
                      />
                    </CommandItem>
                  );
                })}
              </CommandGroup>
            </CommandList>
          </Command>
        </div>
        <DialogFooter className='sm:justify-center px-6 pb-6'>
          <Button
            onClick={() => onCreateClient(searchQuery)}
            className='cursor-pointer text-center'
          >
            <UserPlusIcon className='mr-2 size-4' />
            Añadir nuevo cliente
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};
