import { Head, Link, router, useForm, usePage } from '@inertiajs/react';
import type { FormEvent } from 'react';
import ConfirmActionDialog from '@/components/classrooms/confirm-action-dialog';
import CreditCostField from '@/components/classrooms/credit-cost-field';
import Heading from '@/components/heading';
import InputError from '@/components/input-error';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { Separator } from '@/components/ui/separator';
import { Switch } from '@/components/ui/switch';
import { Textarea } from '@/components/ui/textarea';
import type { Classroom, ClassroomStatus } from '@/components/classrooms/types';
import billing from '@/routes/billing';
import classrooms, { index as classroomsIndex } from '@/routes/classrooms';

type Props = {
    classroom: Classroom;
    creditsAvailable?: number;
};

export default function ClassroomsEdit({
    classroom,
    creditsAvailable = 0,
}: Props) {
    const form = useForm({
        name: classroom.name,
        course_title: classroom.course_title ?? '',
        formatemp_project_code: classroom.formatemp_project_code ?? '',
        starts_on: classroom.starts_on ?? '',
        ends_on: classroom.ends_on ?? '',
        max_participants: classroom.max_participants?.toString() ?? '',
        max_hours: classroom.max_hours?.toString() ?? '',
        record_meetings: classroom.record_meetings,
        max_cameras: classroom.max_cameras?.toString() ?? '',
        moderator_name: classroom.moderator_name ?? '',
        moderator_email: classroom.moderator_email ?? '',
        access_password: classroom.access_password ?? '',
        notes: classroom.notes ?? '',
        status: classroom.status,
    });

    const { errors: pageErrors } = usePage<{
        errors: { credits?: string };
    }>().props;

    // I limiti sono la base del costo in crediti: si cambiano solo finché
    // l'aula è in bozza, cioè prima che qualcuno ci entri.
    const sizeLocked = classroom.status !== 'draft';

    function submit(e: FormEvent) {
        e.preventDefault();
        form.patch(classrooms.update({ classroom: classroom.uuid }).url);
    }

    function destroy() {
        router.delete(classrooms.destroy({ classroom: classroom.uuid }).url);
    }

    return (
        <>
            <Head title={`Modifica ${classroom.name}`} />

            <div className="mx-auto flex w-full max-w-2xl flex-1 flex-col gap-6 p-4">
                <Heading
                    title="Modifica aula"
                    description={`Codice ${classroom.code}`}
                />

                {pageErrors.credits && (
                    <Alert variant="destructive">
                        <AlertTitle>Impossibile salvare l&apos;aula</AlertTitle>
                        <AlertDescription>
                            {pageErrors.credits}{' '}
                            <Link
                                href={billing.index()}
                                className="underline underline-offset-4"
                            >
                                Ricarica i crediti
                            </Link>
                            .
                        </AlertDescription>
                    </Alert>
                )}

                <form onSubmit={submit} className="space-y-6">
                    <div className="grid gap-2">
                        <Label htmlFor="name">Nome aula</Label>
                        <Input
                            id="name"
                            value={form.data.name}
                            onChange={(e) =>
                                form.setData('name', e.target.value)
                            }
                            required
                        />
                        <InputError message={form.errors.name} />
                    </div>

                    <div className="grid gap-2">
                        <Label htmlFor="course_title">Titolo del corso</Label>
                        <Input
                            id="course_title"
                            value={form.data.course_title}
                            onChange={(e) =>
                                form.setData('course_title', e.target.value)
                            }
                        />
                        <InputError message={form.errors.course_title} />
                    </div>

                    <div className="grid gap-2">
                        <Label htmlFor="formatemp_project_code">
                            Codice progetto Forma.Temp
                        </Label>
                        <Input
                            id="formatemp_project_code"
                            value={form.data.formatemp_project_code}
                            onChange={(e) =>
                                form.setData(
                                    'formatemp_project_code',
                                    e.target.value,
                                )
                            }
                        />
                        <InputError
                            message={form.errors.formatemp_project_code}
                        />
                    </div>

                    <CreditCostField
                        participants={form.data.max_participants}
                        hours={form.data.max_hours}
                        onParticipantsChange={(value) =>
                            form.setData('max_participants', value)
                        }
                        onHoursChange={(value) =>
                            form.setData('max_hours', value)
                        }
                        creditsAvailable={creditsAvailable}
                        participantsError={form.errors.max_participants}
                        hoursError={form.errors.max_hours}
                        baselineCost={classroom.credits_cost ?? 0}
                        locked={sizeLocked}
                        lockedReason="I limiti si cambiano solo finché l'aula è in bozza."
                    />

                    <div className="grid grid-cols-2 gap-4">
                        <div className="grid gap-2">
                            <Label htmlFor="starts_on">Data inizio</Label>
                            <Input
                                id="starts_on"
                                type="date"
                                value={form.data.starts_on}
                                onChange={(e) =>
                                    form.setData('starts_on', e.target.value)
                                }
                            />
                            <InputError message={form.errors.starts_on} />
                        </div>
                        <div className="grid gap-2">
                            <Label htmlFor="ends_on">Data fine</Label>
                            <Input
                                id="ends_on"
                                type="date"
                                value={form.data.ends_on}
                                onChange={(e) =>
                                    form.setData('ends_on', e.target.value)
                                }
                            />
                            <InputError message={form.errors.ends_on} />
                        </div>
                    </div>

                    <div className="grid gap-2">
                        <Label htmlFor="status">Stato</Label>
                        <Select
                            value={form.data.status}
                            onValueChange={(value) =>
                                form.setData('status', value as ClassroomStatus)
                            }
                        >
                            <SelectTrigger id="status" className="w-full">
                                <SelectValue />
                            </SelectTrigger>
                            <SelectContent>
                                <SelectItem value="draft">Bozza</SelectItem>
                                <SelectItem value="active">Attiva</SelectItem>
                                <SelectItem value="closed">Chiusa</SelectItem>
                            </SelectContent>
                        </Select>
                        <InputError message={form.errors.status} />
                    </div>

                    <div className="flex items-center justify-between rounded-lg border p-3">
                        <div className="space-y-0.5">
                            <Label htmlFor="record_meetings">
                                Registra le lezioni
                            </Label>
                            <p className="text-muted-foreground text-sm">
                                Imposta la registrazione come predefinita per le
                                nuove lezioni di questa aula.
                            </p>
                        </div>
                        <Switch
                            id="record_meetings"
                            checked={form.data.record_meetings}
                            onCheckedChange={(checked) =>
                                form.setData('record_meetings', checked)
                            }
                        />
                    </div>

                    <div className="grid gap-2">
                        <Label htmlFor="max_cameras">
                            Numero massimo webcam (opzionale)
                        </Label>
                        <Input
                            id="max_cameras"
                            type="number"
                            min={0}
                            value={form.data.max_cameras}
                            onChange={(e) =>
                                form.setData('max_cameras', e.target.value)
                            }
                        />
                        <InputError message={form.errors.max_cameras} />
                    </div>

                    <div className="grid grid-cols-2 gap-4">
                        <div className="grid gap-2">
                            <Label htmlFor="moderator_name">
                                Nome moderatore
                            </Label>
                            <Input
                                id="moderator_name"
                                value={form.data.moderator_name}
                                onChange={(e) =>
                                    form.setData(
                                        'moderator_name',
                                        e.target.value,
                                    )
                                }
                            />
                            <InputError message={form.errors.moderator_name} />
                        </div>
                        <div className="grid gap-2">
                            <Label htmlFor="moderator_email">
                                Email moderatore
                            </Label>
                            <Input
                                id="moderator_email"
                                type="email"
                                value={form.data.moderator_email}
                                onChange={(e) =>
                                    form.setData(
                                        'moderator_email',
                                        e.target.value,
                                    )
                                }
                            />
                            <InputError message={form.errors.moderator_email} />
                        </div>
                    </div>

                    <div className="grid gap-2">
                        <Label htmlFor="access_password">
                            Password d&apos;accesso aggiuntiva (opzionale)
                        </Label>
                        <Input
                            id="access_password"
                            value={form.data.access_password}
                            onChange={(e) =>
                                form.setData('access_password', e.target.value)
                            }
                            maxLength={32}
                        />
                        <p className="text-muted-foreground text-sm">
                            Se impostata, sul link pubblico della lezione viene
                            richiesta oltre al codice fiscale.
                        </p>
                        <InputError message={form.errors.access_password} />
                    </div>

                    <div className="grid gap-2">
                        <Label htmlFor="notes">Note</Label>
                        <Textarea
                            id="notes"
                            value={form.data.notes}
                            onChange={(e) =>
                                form.setData('notes', e.target.value)
                            }
                        />
                        <InputError message={form.errors.notes} />
                    </div>

                    <div className="flex items-center gap-4">
                        <Button type="submit" disabled={form.processing}>
                            Salva modifiche
                        </Button>
                        <Link
                            href={classrooms.show(classroom.uuid)}
                            className="text-muted-foreground text-sm hover:underline"
                        >
                            Annulla
                        </Link>
                    </div>
                </form>

                <Separator />

                <div className="border-destructive/30 flex items-center justify-between rounded-lg border p-4">
                    <div className="space-y-0.5">
                        <p className="font-medium">Elimina aula</p>
                        <p className="text-muted-foreground text-sm">
                            Questa azione è irreversibile e rimuove
                            definitivamente l&apos;aula, i partecipanti e le
                            lezioni collegate.
                        </p>
                    </div>
                    <ConfirmActionDialog
                        trigger={
                            <Button variant="destructive">Elimina aula</Button>
                        }
                        title="Eliminare questa aula?"
                        description={`Stai per eliminare definitivamente "${classroom.name}". Questa azione non può essere annullata.`}
                        confirmLabel="Elimina"
                        destructive
                        onConfirm={destroy}
                    />
                </div>
            </div>
        </>
    );
}

ClassroomsEdit.layout = ({ classroom }: Props) => ({
    breadcrumbs: [
        { title: 'Aule', href: classroomsIndex() },
        { title: classroom.name, href: classrooms.show(classroom.uuid) },
        { title: 'Modifica', href: classrooms.edit(classroom.uuid) },
    ],
});
