import { cn } from '@/app/utils';
import { Button } from '@/views/components/ui/button';
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
} from '@/views/components/ui/command';
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from '@/views/components/ui/popover';
import { Check, ChevronsUpDown } from 'lucide-react';
import { useState } from 'react';

type SelectPopoverProps = {
  label: string;
  items: { id: number; descricao: string }[];
  value: string;
  setValue: (value: string) => void;
  placeholder: string;
  disableUnselect?: boolean;
};

export function SelectPopover({
  label,
  items,
  value,
  setValue,
  placeholder,
  disableUnselect,
}: SelectPopoverProps) {
  const [open, setOpen] = useState(false);

  const normalizeForSort = (str: string) =>
    str.replace(/^[\d.\-\s]+/, '').toLowerCase();

  const sortedItems = [...items]
    .sort((a, b) =>
      normalizeForSort(a.descricao).localeCompare(
        normalizeForSort(b.descricao),
        'pt-BR',
        { sensitivity: 'base' }
      )
    )
    .sort((a, b) => {
      const aVal = a.id.toString() + '-' + a.descricao;
      const bVal = b.id.toString() + '-' + b.descricao;

      if (aVal === value) return -1;
      if (bVal === value) return 1;
      return 0;
    });

  return (
    <Popover open={open} onOpenChange={setOpen}>
      <PopoverTrigger asChild>
        <Button
          variant="outline"
          role="combobox"
          aria-expanded={open}
          className="w-full md:w-[200px] justify-between truncate capitalize"
          title={
            value
              ? items
                  .find(
                    (item) =>
                      item.id.toString() + '-' + item.descricao === value
                  )
                  ?.descricao.replace(/[.\d-]/g, '')
              : placeholder
          }
        >
          <span className="truncate capitalize">
            {value
              ? items
                  .find(
                    (item) =>
                      item.id.toString() + '-' + item.descricao === value
                  )
                  ?.descricao.replace(/[.\d-]/g, '')
              : placeholder}
          </span>
          <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
        </Button>
      </PopoverTrigger>
      <PopoverContent className="w-[200px] p-0">
        <Command>
          <CommandInput placeholder={`Buscar ${label.toLowerCase()}...`} />
          <CommandList>
            <CommandEmpty>
              Nenhum {label.toLowerCase()} encontrado.
            </CommandEmpty>
            <CommandGroup>
              {sortedItems.map((item) => {
                const itemValue = item.id.toString() + '-' + item.descricao;
                const displayText = item.descricao.replace(/[.\d-]/g, '');

                return (
                  <CommandItem
                    key={itemValue}
                    value={itemValue}
                    onSelect={(currentValue) => {
                      if (disableUnselect && currentValue === value) {
                        return;
                      }

                      setValue(currentValue === value ? '' : currentValue);
                      setOpen(false);
                    }}
                    title={displayText}
                  >
                    <Check
                      className={cn(
                        'mr-2 h-4 w-4',
                        value === itemValue ? 'opacity-100' : 'opacity-0'
                      )}
                    />
                    {displayText.toUpperCase()}
                  </CommandItem>
                );
              })}
            </CommandGroup>
          </CommandList>
        </Command>
      </PopoverContent>
    </Popover>
  );
}
