import type { ComponentProps, ReactNode } from 'react';
import InputError from '@/components/input-error';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { Switch } from '@/components/ui/switch';
import { Textarea } from '@/components/ui/textarea';
import { cn } from '@/lib/utils';

type FieldProps = {
    /** Id of the control the label belongs to. */
    id: string;
    label: ReactNode;
    error?: string;
    hint?: ReactNode;
    /** Shown at the end of the label row, e.g. a character counter. */
    aside?: ReactNode;
    className?: string;
    children: ReactNode;
};

/** Label, control, helper text and validation error of one form field. */
export function Field({
    id,
    label,
    error,
    hint,
    aside,
    className,
    children,
}: FieldProps) {
    return (
        <div className={cn('grid grid-cols-1 content-start gap-2', className)}>
            <div className="flex items-end justify-between gap-3">
                <Label htmlFor={id} className="leading-normal">
                    {label}
                </Label>
                {aside}
            </div>
            {children}
            {hint && (
                <p id={`${id}-hint`} className="text-xs text-muted-foreground">
                    {hint}
                </p>
            )}
            <InputError message={error} />
        </div>
    );
}

type ControlProps = Omit<FieldProps, 'children'> & {
    value: string;
    onChange: (value: string) => void;
};

type TextFieldProps = ControlProps &
    Omit<ComponentProps<typeof Input>, keyof ControlProps>;

/** A single-line text input with its label, hint and error. */
export function TextField({
    id,
    label,
    value,
    onChange,
    error,
    hint,
    aside,
    className,
    ...props
}: TextFieldProps) {
    return (
        <Field
            id={id}
            label={label}
            error={error}
            hint={hint}
            aside={aside}
            className={className}
        >
            <Input
                id={id}
                value={value}
                onChange={(event) => onChange(event.target.value)}
                aria-invalid={error ? true : undefined}
                aria-describedby={hint ? `${id}-hint` : undefined}
                {...props}
            />
        </Field>
    );
}

type TextareaFieldProps = ControlProps &
    Omit<ComponentProps<typeof Textarea>, keyof ControlProps>;

/** A multi-line text input with its label, hint and error. */
export function TextareaField({
    id,
    label,
    value,
    onChange,
    error,
    hint,
    aside,
    className,
    ...props
}: TextareaFieldProps) {
    return (
        <Field
            id={id}
            label={label}
            error={error}
            hint={hint}
            aside={aside}
            className={className}
        >
            <Textarea
                id={id}
                value={value}
                onChange={(event) => onChange(event.target.value)}
                aria-invalid={error ? true : undefined}
                aria-describedby={hint ? `${id}-hint` : undefined}
                {...props}
            />
        </Field>
    );
}

type SelectFieldProps = ControlProps & {
    options: { value: string; label: string }[];
    placeholder?: string;
};

/** A drop-down with its label, hint and error. An empty value selects nothing. */
export function SelectField({
    id,
    label,
    value,
    onChange,
    options,
    placeholder,
    error,
    hint,
    aside,
    className,
}: SelectFieldProps) {
    return (
        <Field
            id={id}
            label={label}
            error={error}
            hint={hint}
            aside={aside}
            className={className}
        >
            <Select value={value} onValueChange={onChange}>
                <SelectTrigger
                    id={id}
                    className="w-full"
                    aria-invalid={error ? true : undefined}
                >
                    <SelectValue placeholder={placeholder} />
                </SelectTrigger>
                {/* Forms are long: open upwards when there is no room below. */}
                <SelectContent avoidCollisions>
                    {options.map((option) => (
                        <SelectItem key={option.value} value={option.value}>
                            {option.label}
                        </SelectItem>
                    ))}
                </SelectContent>
            </Select>
        </Field>
    );
}

type SwitchFieldProps = {
    id: string;
    label: ReactNode;
    checked: boolean;
    onChange: (checked: boolean) => void;
    hint?: ReactNode;
    error?: string;
};

/** An on/off setting: the switch sits in front of its label and explanation. */
export function SwitchField({
    id,
    label,
    checked,
    onChange,
    hint,
    error,
}: SwitchFieldProps) {
    return (
        <div className="grid grid-cols-1 gap-2">
            <div className="flex items-start gap-3">
                <Switch
                    id={id}
                    checked={checked}
                    onCheckedChange={onChange}
                    className="mt-0.5"
                    aria-describedby={hint ? `${id}-hint` : undefined}
                />
                <div className="grid grid-cols-1 gap-1">
                    <Label htmlFor={id} className="leading-normal">
                        {label}
                    </Label>
                    {hint && (
                        <p
                            id={`${id}-hint`}
                            className="text-xs text-muted-foreground"
                        >
                            {hint}
                        </p>
                    )}
                </div>
            </div>
            <InputError message={error} />
        </div>
    );
}
