import { useId } from 'react';
import {
    Field,
    FieldDescription,
    FieldError,
    FieldLabel,
} from '@/components/ui/field';
import { Label } from '@/components/ui/label';
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
import { cn } from '@/lib/utils';
import { useSectionForm } from '../lib/section-form-context';

type Option = {
    value: string;
    label: string;
};

type RadioCardsFieldProps = {
    name: string;
    label: string;
    required?: boolean;
    options: readonly Option[];
    columns?: 2 | 3 | 4;
    hint?: string;
};

export function RadioCardsField({
    name,
    label,
    required,
    options,
    columns = 2,
    hint,
}: RadioCardsFieldProps) {
    const { data, setData, errors } = useSectionForm();
    const id = useId();
    const value = (data[name] as string | null) ?? '';
    const error = errors[name];

    return (
        <Field data-invalid={!!error}>
            <FieldLabel htmlFor={id}>
                {label}
                {required && (
                    <span className="ml-0.5 text-destructive">*</span>
                )}
            </FieldLabel>

            <RadioGroup
                id={id}
                value={value}
                onValueChange={(v) => setData(name, v)}
                className={cn(
                    'grid gap-2',
                    columns === 2 && 'sm:grid-cols-2',
                    columns === 3 && 'sm:grid-cols-3',
                    columns === 4 && 'sm:grid-cols-4',
                )}
            >
                {options.map((opt) => {
                    const selected = value === opt.value;
                    return (
                        <Label
                            key={opt.value}
                            className={cn(
                                'flex cursor-pointer items-center gap-2.5 rounded-lg border px-4 py-3 text-sm transition-colors',
                                selected
                                    ? 'border-primary bg-primary/5 font-medium text-primary'
                                    : 'text-muted-foreground hover:bg-muted/50 hover:text-foreground',
                            )}
                        >
                            <RadioGroupItem value={opt.value} />
                            {opt.label}
                        </Label>
                    );
                })}
            </RadioGroup>

            {error ? (
                <FieldError>{error}</FieldError>
            ) : hint ? (
                <FieldDescription>{hint}</FieldDescription>
            ) : null}
        </Field>
    );
}
