'use client';

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

export interface ColorOption {
    value: string;
    label: string;
    color: string;
    disabled?: boolean;
}

interface ColorSelectFieldProps {
    name: string;
    options: ColorOption[];
    placeholder?: string;
    disabled?: boolean;
    className?: string;
}

export const ColorSelectField = ({ name, options, placeholder, disabled, className }: ColorSelectFieldProps) => {
    const { control, watch } = useFormContext();
    const selectedValue = watch(name);

    // Find the selected option to display its color and label
    const selectedOption = options.find((option) => option.value === selectedValue);

    return (
        <Controller
            control={control}
            name={name}
            render={({ field }) => (
                <Select value={field.value} onValueChange={field.onChange} disabled={disabled}>
                    <SelectTrigger className={cn(className)}>
                        <SelectValue placeholder={placeholder || 'Select a color'}>
                            {selectedOption && (
                                <div className="flex items-center space-x-2">
                                    <div
                                        className="h-4 w-4 rounded-full border border-gray-300 dark:border-gray-600"
                                        style={{ backgroundColor: selectedOption.color }}
                                    />
                                    <span>{selectedOption.label}</span>
                                </div>
                            )}
                        </SelectValue>
                    </SelectTrigger>
                    <SelectContent>
                        {options.map((option) => (
                            <SelectItem key={option.value} value={String(option.value)} disabled={option.disabled} className="cursor-pointer">
                                <div className="flex items-center space-x-2">
                                    <div
                                        className="h-4 w-4 flex-shrink-0 rounded-full border border-gray-300 dark:border-gray-600"
                                        style={{ backgroundColor: option.color }}
                                    />
                                    <span>{option.label}</span>
                                </div>
                            </SelectItem>
                        ))}
                    </SelectContent>
                </Select>
            )}
        />
    );
};
