import { Checkbox } from '@/components/ui/checkbox';
import { Field, FieldError, FieldLabel } from '@/components/ui/field';
import { Input } from '@/components/ui/input';
import type { ReconocimientoDeclaratoriaData } from '@/generated/types';
import {
    TIPO_DECLARATORIA_LABELS,
    type TipoDeclaratoriaKey,
} from '../lib/enum-labels';
import { useSectionForm } from '../lib/section-form-context';

const DECLARATORIA_KEYS = Object.keys(
    TIPO_DECLARATORIA_LABELS,
) as TipoDeclaratoriaKey[];

export function ReconocimientoDeclaratoria() {
    const { data, setData, errors } =
        useSectionForm<ReconocimientoDeclaratoriaData>();
    const hasError = DECLARATORIA_KEYS.some((key) => !!errors[key]);

    const toggleDeclaratoria = (key: TipoDeclaratoriaKey, checked: boolean) => {
        setData(key, checked ? (data[key] ?? '') : null);
    };

    const updateValue = (key: TipoDeclaratoriaKey, value: string) => {
        setData(key, value);
    };

    return (
        <Field data-invalid={hasError}>
            <FieldLabel>Declaratorias reconocidas</FieldLabel>
            <div className="overflow-hidden rounded-lg border">
                {DECLARATORIA_KEYS.map((key) => {
                    const value = data[key];
                    const checked = value !== null;

                    return (
                        <div
                            key={key}
                            className="grid gap-3 border-b p-4 last:border-b-0 sm:grid-cols-[180px_minmax(0,1fr)] sm:items-center"
                        >
                            <label className="flex items-center gap-3 text-sm font-medium">
                                <Checkbox
                                    checked={checked}
                                    onCheckedChange={(value) =>
                                        toggleDeclaratoria(key, value === true)
                                    }
                                />
                                {TIPO_DECLARATORIA_LABELS[key]}
                            </label>
                            <Input
                                value={value ?? ''}
                                onChange={(event) =>
                                    updateValue(key, event.target.value)
                                }
                                disabled={!checked}
                                placeholder="Detalle de la declaratoria"
                            />
                        </div>
                    );
                })}
            </div>
            {DECLARATORIA_KEYS.map((key) =>
                errors[key] ? (
                    <FieldError key={key}>{errors[key]}</FieldError>
                ) : null,
            )}
        </Field>
    );
}
