'use client';

import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@admin/components/ui/select';
import { cn } from '@admin/utils/common';
import { Controller, useFormContext } from 'react-hook-form';

export interface Option {
    value: string | number;
    label: string;
    disabled?: boolean;
}

interface SelectFieldProps {
    name: string;
    options: Option[] | string[];
    placeholder?: string;
    disabled?: boolean;
    className?: string;
}

export const SelectField = ({ name, options, placeholder, disabled, className }: SelectFieldProps) => {
    const { control } = useFormContext();

    // Helper function to normalize options to Option[] format
    const normalizeOptions = (opts: Option[] | string[]): Option[] => {
        return opts.map((opt) => {
            if (typeof opt === 'string') {
                return { value: opt, label: opt };
            }
            return opt;
        });
    };

    const normalizedOptions = normalizeOptions(options);

    return (
        <Controller
            control={control}
            name={name}
            render={({ field }) => (
                <Select 
                    value={field.value !== undefined && field.value !== null ? String(field.value) : undefined} 
                    onValueChange={(value) => {
                        // Convert back to number if the original option value was a number
                        const originalOption = normalizedOptions.find(opt => String(opt.value) === value);
                        field.onChange(originalOption ? originalOption.value : value);
                    }} 
                    disabled={disabled}
                >
                    <SelectTrigger className={cn(className)}>
                        <SelectValue placeholder={placeholder || 'Select an option'} />
                    </SelectTrigger>
                    <SelectContent>
                        {normalizedOptions.map((option) => (
                            <SelectItem key={option.value} value={String(option.value)} disabled={option.disabled}>
                                {option.label}
                            </SelectItem>
                        ))}
                    </SelectContent>
                </Select>
            )}
        />
    );
};
