import { Select as ShadSelect, SelectContent, SelectGroup } from '@/components/ui/select';
import { SelectItem, SelectLabel, SelectTrigger, SelectValue } from '@/components/ui/select';
import { cn } from 'helpers/cn';

export const Select = (props: SelectProps) => {
  const { options, value, onChange, onValueChange, label } = props;
  const { name = '', className, placeholder = 'Select...', update } = props;

  if (!options) return null;

  const onLocalValueChange = (newValue: string) => {
    onChange && onChange({ target: { name, value: newValue } });
    onValueChange && onValueChange(newValue);
    update && update((state: any) => ({ ...state, [name]: newValue }));
  };

  // Convert value to string for Radix compatibility, undefined for no selection
  const selectValue = value != null ? String(value) : undefined;

  return (
    <ShadSelect {...props} value={selectValue} onValueChange={onLocalValueChange}>
      <SelectTrigger className={cn('h-11', className)}>
        <SelectValue placeholder={placeholder} />
      </SelectTrigger>
      <SelectContent>
        <SelectGroup>
          {label && <SelectLabel>{label}</SelectLabel>}
          {options.map((option) => {
            const theOption = typeof option === 'string' ? { value: option } : option;
            const itemValue = String(theOption.value ?? option);
            const itemLabel = String((theOption as SelectOption).label ?? option);
            if (typeof option === 'object' && option.hidden) return null;
            return (
              <SelectItem key={itemValue} value={itemValue}>
                {itemLabel}
              </SelectItem>
            );
          })}
        </SelectGroup>
      </SelectContent>
    </ShadSelect>
  );
};

type SelectProps = {
  options: SelectOption[] | string[];
  value?: string | null;
  onChange?: (ev: { target: { name: string; value: string } }) => void;
  onValueChange?: (value: string) => void;
  label?: string;
  name?: string;
  className?: string;
  placeholder?: string;
  update?: React.Dispatch<React.SetStateAction<any>>;
};
