import { Link } from '@inertiajs/react';
import InputError from '@/components/input-error';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useCreditRule } from '@/hooks/use-credit-rule';
import { creditCost, creditsLabel, parseCount } from '@/lib/credits';
import { cn } from '@/lib/utils';
import { index as billingIndex } from '@/routes/billing';

type Props = {
    participants: string;
    hours: string;
    onParticipantsChange: (value: string) => void;
    onHoursChange: (value: string) => void;
    /** Crediti disponibili in questo momento. */
    creditsAvailable: number;
    participantsError?: string;
    hoursError?: string;
    /** Crediti già addebitati per quest'aula: mostra la differenza invece del totale. */
    baselineCost?: number;
    /** I limiti non si possono più cambiare (aula non in bozza). */
    locked?: boolean;
    lockedReason?: string;
};

/**
 * Discenti massimi e ore massime con il costo in crediti calcolato in diretta.
 * La regola è scritta per esteso ("1 credito = 4 ore d'aula fino a 30
 * discenti") perché è con quella che l'utente decide quanto grande fare
 * l'aula: il totale da solo non si spiega.
 */
export default function CreditCostField({
    participants,
    hours,
    onParticipantsChange,
    onHoursChange,
    creditsAvailable,
    participantsError,
    hoursError,
    baselineCost = 0,
    locked = false,
    lockedReason,
}: Props) {
    const rule = useCreditRule();
    const people = parseCount(participants);
    const duration = parseCount(hours);
    const cost = creditCost(people, duration, rule);
    const delta = cost - baselineCost;
    const missing = Math.max(0, delta - creditsAvailable);
    const hasSize = people > 0 && duration > 0;

    return (
        <fieldset className="grid gap-4" disabled={locked}>
            <legend className="sr-only">Dimensione dell&apos;aula</legend>

            <p className="text-muted-foreground text-sm">
                1 credito = {rule.hoursPerCredit} ore d&apos;aula fino a{' '}
                {rule.participantsBand} discenti. Oltre le ore o i discenti, il
                costo sale a scatti.
            </p>

            <div className="grid grid-cols-2 gap-4">
                <div className="grid gap-2">
                    <Label htmlFor="max_participants">Discenti massimi</Label>
                    <Input
                        id="max_participants"
                        type="number"
                        inputMode="numeric"
                        min={1}
                        required
                        value={participants}
                        onChange={(e) => onParticipantsChange(e.target.value)}
                    />
                    <InputError message={participantsError} />
                </div>
                <div className="grid gap-2">
                    <Label htmlFor="max_hours">Ore massime</Label>
                    <Input
                        id="max_hours"
                        type="number"
                        inputMode="numeric"
                        min={1}
                        required
                        value={hours}
                        onChange={(e) => onHoursChange(e.target.value)}
                    />
                    <InputError message={hoursError} />
                </div>
            </div>

            <div
                className={cn(
                    'rounded-lg border p-3',
                    missing > 0 ? 'border-destructive/40' : 'border-border',
                )}
            >
                <div className="flex flex-wrap items-baseline justify-between gap-x-4 gap-y-1">
                    <p
                        className="text-muted-foreground text-sm tabular-nums"
                        aria-hidden
                    >
                        {hasSize
                            ? `${duration} ore in scatti da ${rule.hoursPerCredit}, ${people} discenti in fasce da ${rule.participantsBand}`
                            : 'Imposta discenti e ore per vedere il costo'}
                    </p>
                    <p className="text-sm">
                        <span className="text-muted-foreground">Costo </span>
                        <span className="font-medium tabular-nums">
                            {creditsLabel(cost)}
                        </span>
                    </p>
                </div>

                <div className="text-muted-foreground mt-1 flex flex-wrap items-baseline justify-between gap-x-4 gap-y-1 text-sm">
                    <span>
                        Saldo disponibile{' '}
                        <span className="tabular-nums">
                            {creditsLabel(creditsAvailable)}
                        </span>
                    </span>
                    {baselineCost > 0 && delta !== 0 && (
                        <span className="tabular-nums">
                            {delta > 0
                                ? `Ti verranno addebitati ${creditsLabel(delta)}`
                                : `Ti verranno riaccreditati ${creditsLabel(-delta)}`}
                        </span>
                    )}
                </div>

                {missing > 0 && (
                    <p className="text-destructive mt-2 text-sm">
                        Ti mancano {creditsLabel(missing)}.{' '}
                        <Link
                            href={billingIndex()}
                            className="underline underline-offset-4"
                        >
                            Ricarica i crediti
                        </Link>
                        .
                    </p>
                )}
            </div>

            {locked && lockedReason && (
                <p className="text-muted-foreground text-sm">{lockedReason}</p>
            )}
        </fieldset>
    );
}
