import { Button } from '@/components/ui/button';
import { FormItem, FormLabel, FormMessage } from '@/components/ui/form';
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from '@/components/ui/popover';
import { fnBool, fnString } from '@/types';
import React, { useEffect, useState } from 'react';
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
} from '@/components/ui/command';
import { DropIcon } from '@/components/common/forms/DropIcon';

interface Option {
  id: string | number;
  name: string;
}

interface SearchableSelectProps {
  field: any;
  label: string;
  placeholder: string;
  options: Option[];
  isOpen: boolean;
  onOpenChange: fnBool;
  onSelect: fnString;
  defaultValue?: any;
  required?: boolean;
  displayName?: string;
  disabled?: boolean;
}

export const SearchableSelect: React.FC<SearchableSelectProps> = React.memo(
  ({
    field,
    label,
    placeholder,
    options,
    isOpen,
    onOpenChange,
    onSelect,
    defaultValue,
    required = false,
    disabled = false,
  }) => {
    const [search, setSearch] = useState('');

    const handleSelect = (value: any) => {
      field.onChange(value);
      onSelect(value);
    };

    const filteredOptions = options.filter((item) =>
      item.name.toLowerCase().includes(search.toLowerCase()),
    );

    return (
      <FormItem className="w-full md:w-1/2 lg:w-1/4 p-2">
        <FormLabel className="font-bold">
          {required && <span className="text-red-600 pl-1">*</span>}
          {label}
        </FormLabel>
        <Popover
          open={disabled ? false : isOpen}
          onOpenChange={onOpenChange}
          modal
        >
          <PopoverTrigger asChild>
            <Button
              disabled={disabled}
              className="w-full text-left flex justify-between button-text-length disabled:!bg-[#ccc] disabled:cursor-not-allowed"
              variant="outline"
              aria-expanded={isOpen}
            >
              <span>
                {field.value
                  ? options.find(
                      (item) => String(item.id) === String(field.value),
                    )?.name
                  : placeholder}
              </span>
              <DropIcon />
            </Button>
          </PopoverTrigger>
          <PopoverContent className="p-0 select-picker-widget-popover">
            <Command shouldFilter={false}>
              <CommandInput
                placeholder={`Search ${label}...`}
                value={search}
                onValueChange={setSearch}
              />
              <CommandEmpty>No record found</CommandEmpty>
              <CommandGroup>
                {filteredOptions.map((item) => (
                  <CommandItem
                    key={`${field.name}-${item.id}`}
                    className="cursor-pointer single-select-option"
                    onSelect={() => handleSelect(item.id)}
                  >
                    <span
                      className={
                        String(item.id) === String(field.value)
                          ? 'font-semibold'
                          : ''
                      }
                    >
                      {item.name}
                    </span>
                  </CommandItem>
                ))}
              </CommandGroup>
            </Command>
          </PopoverContent>
        </Popover>
        <FormMessage />
      </FormItem>
    );
  },
);
SearchableSelect.displayName = 'SearchableSelect';
