'use client';

import { ReactNode } from 'react';
import { useFormContext } from 'react-hook-form';
import { FormControl, FormDescription, FormField, FormItem, FormMessage } from '@/components/ui/form';
import { SearchableSelect } from './searchable-select';
import { Label } from './label';

interface Option {
  label: ReactNode;
  value: string | number | object;
}

interface FormSearchableSelectProps {
  name: string;
  label?: string;
  description?: string;
  options: Option[];
  onSearch?: (term: string) => void;
  loading?: boolean;
  placeholder?: string;
  className?: string;
  buttonClassName?: string;
  shouldFilter?: boolean;
  defaultValue?: string | number | readonly string[] | undefined;
  required?: boolean;
  error?: string;
}

export function FormSearchableSelect({
  name,
  label,
  description,
  options,
  onSearch,
  loading,
  placeholder,
  className,
  error,
  buttonClassName,
  shouldFilter,
  defaultValue,
  required,
}: FormSearchableSelectProps) {
  const form = useFormContext();

  return (
    <FormField
      control={form.control}
      name={name}
      render={({ field }) => (
        <FormItem className={className}>
          {label && (
            <Label>
              {label}
              {required && <span className='text-red-500 ml-1'>*</span>}
            </Label>
          )}
          <FormControl>
            <SearchableSelect
              options={options}
              value={field.value ?? defaultValue}
              onChange={field.onChange}
              onSearch={onSearch}
              loading={loading}
              placeholder={placeholder}
              buttonClassName={buttonClassName}
              shouldFilter={shouldFilter}
              isClearable
            />
          </FormControl>
          {description && <FormDescription>{description}</FormDescription>}
          {error && <FormMessage>{error}</FormMessage>}
        </FormItem>
      )}
    />
  );
}
