'use client';

import { Label } from '@admin/components/ui/label';
import { RadioGroup, RadioGroupItem } from '@admin/components/ui/radio-group';
import { cn } from '@admin/utils/common';
import { Controller, useFormContext } from 'react-hook-form';

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

interface RadioFieldProps {
    name: string;
    options: Option[] | string[];
    disabled?: boolean;
    className?: string;
    orientation?: 'horizontal' | 'vertical';
}

export const RadioField = ({ name, options, disabled, className, orientation }: RadioFieldProps) => {
    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 }) => (
                <RadioGroup
                    value={field.value}
                    onValueChange={field.onChange}
                    disabled={disabled}
                    className={cn(orientation === 'horizontal' ? 'flex flex-wrap gap-4' : 'space-y-2', className)}
                >
                    {normalizedOptions.map((option) => (
                        <div key={option.value} className="flex items-center space-x-2">
                            <RadioGroupItem value={String(option.value)} disabled={option.disabled} />
                            <Label className="cursor-pointer">{option.label}</Label>
                        </div>
                    ))}
                </RadioGroup>
            )}
        />
    );
};
