import { Label } from '@/components/ui/label';
import { cn } from '@/lib/utils';

/**
 * One labelled control, with its hint and its error, so every form in the app
 * reads the same: a quiet label, the input, and a red line only when something
 * is actually wrong.
 *
 * The error text comes from the Inertia form render props, so passing
 * `error={errors.name}` keeps validation behaviour identical to the previous
 * `<InputError message={...} />` usage.
 */
export function Field({
    label,
    htmlFor,
    hint,
    error,
    required = false,
    className,
    children,
}: {
    label: string;
    htmlFor?: string;
    hint?: string | null;
    error?: string | null;
    required?: boolean;
    className?: string;
    children: React.ReactNode;
}) {
    return (
        <div className={cn('grid gap-1.5', className)}>
            <div className="flex items-baseline justify-between gap-3">
                <Label
                    htmlFor={htmlFor}
                    className="text-[13px] font-medium tracking-tight"
                >
                    {label}
                    {required ? (
                        <span className="text-danger ml-0.5" aria-hidden>
                            *
                        </span>
                    ) : null}
                </Label>
                {hint ? (
                    <span className="text-muted-foreground text-xs">
                        {hint}
                    </span>
                ) : null}
            </div>

            {children}

            {error ? (
                <p className="text-danger text-xs font-medium" role="alert">
                    {error}
                </p>
            ) : null}
        </div>
    );
}

/**
 * The save row at the foot of a form section: the buttons on the right, an
 * optional note on the left, separated by a hairline.
 *
 * It assumes two things about where it is placed, both of which the settings
 * forms honour: it is the last child of a SectionCard body (so the negative
 * margins cancel the body's `px-5 pb-5` and the hairline spans the card), and
 * the form it lives in is a `flex flex-col gap-5` column, which supplies the
 * space above it.
 */
export function FormActions({
    note,
    className,
    children,
}: {
    note?: React.ReactNode;
    className?: string;
    children: React.ReactNode;
}) {
    return (
        <div
            className={cn(
                'border-hairline -mx-5 -mb-5 flex flex-col-reverse gap-3 border-t px-5 py-3.5 sm:flex-row sm:items-center sm:justify-between',
                className,
            )}
        >
            {note ? (
                <p className="text-muted-foreground text-xs">{note}</p>
            ) : (
                <span />
            )}
            <div className="flex flex-wrap items-center gap-2">{children}</div>
        </div>
    );
}
