import { useId } from 'react';
import {
    Field,
    FieldDescription,
    FieldError,
    FieldLabel,
} from '@/components/ui/field';
import { Textarea } from '@/components/ui/textarea';
import { useSectionForm } from '../lib/section-form-context';

type TextareaFieldProps = {
    name: string;
    label: string;
    required?: boolean;
    placeholder?: string;
    rows?: number;
    maxLength?: number;
    hint?: string;
};

export function TextareaField({
    name,
    label,
    required,
    placeholder,
    rows = 6,
    maxLength,
    hint,
}: TextareaFieldProps) {
    const { data, setData, errors } = useSectionForm();
    const id = useId();
    const value = (data[name] as string) ?? '';
    const error = errors[name];

    return (
        <Field data-invalid={!!error}>
            <FieldLabel htmlFor={id}>
                {label}
                {required && (
                    <span className="ml-0.5 text-destructive">*</span>
                )}
            </FieldLabel>
            <Textarea
                id={id}
                value={value}
                onChange={(e) => setData(name, e.target.value)}
                placeholder={placeholder}
                rows={rows}
                maxLength={maxLength}
                aria-invalid={!!error}
            />
            {error ? (
                <FieldError>{error}</FieldError>
            ) : hint ? (
                <FieldDescription>{hint}</FieldDescription>
            ) : null}
        </Field>
    );
}
