import { Head, Link, router, usePage } from '@inertiajs/react';
import { Fragment, useState } from 'react';
import {
    ClassroomStatusBadge,
    MeetingStatusBadge,
    ParticipantRoleBadge,
} from '@/components/classrooms/badges';
import ConfirmActionDialog from '@/components/classrooms/confirm-action-dialog';
import { formatDateTime, formatSeconds } from '@/components/classrooms/format';
import MeetingReportCard from '@/components/classrooms/meeting-report-card';
import type {
    Attendance,
    Classroom,
    Meeting,
    MeetingEvent,
    Participant,
} from '@/components/classrooms/types';
import { Button } from '@/components/ui/button';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import {
    Tooltip,
    TooltipContent,
    TooltipTrigger,
} from '@/components/ui/tooltip';
import classrooms, { index as classroomsIndex } from '@/routes/classrooms';
import meetings from '@/routes/meetings';

type ParticipantAttendanceRow = Participant & {
    seconds: number;
    intervals: Attendance[];
};

type Props = {
    meeting: Meeting & { scheduled_end_at: string };
    classroom: Classroom;
    participants: ParticipantAttendanceRow[];
    events: MeetingEvent[];
    formatempConfigured: boolean;
};

export default function MeetingsShow({
    meeting,
    classroom,
    participants,
    events,
    formatempConfigured,
}: Props) {
    const { errors } = usePage<{ errors: { formatemp?: string } }>().props;
    const [expanded, setExpanded] = useState<number | null>(null);

    function endMeeting() {
        router.post(
            meetings.end({ meeting: meeting.uuid }).url,
            {},
            { preserveScroll: true },
        );
    }

    function refreshMeeting() {
        router.post(
            meetings.refresh({ meeting: meeting.uuid }).url,
            {},
            { preserveScroll: true },
        );
    }

    function syncFormatemp() {
        router.post(
            meetings.formatemp.sync({ meeting: meeting.uuid }).url,
            {},
            { preserveScroll: true },
        );
    }

    // Consolidating closes the register on Forma.Temp for good, so the confirmation
    // travels with the request: the endpoint rejects it without `confirm`.
    function consolidateFormatemp() {
        router.post(
            meetings.formatemp.consolidate({ meeting: meeting.uuid }).url,
            { confirm: 1 },
            { preserveScroll: true },
        );
    }

    const recentEvents = events.slice(0, 200);

    return (
        <>
            <Head title={meeting.title} />

            <div className="flex flex-1 flex-col gap-6 p-4">
                <div className="flex flex-wrap items-start justify-between gap-4">
                    <div className="space-y-1">
                        <div className="flex items-center gap-2">
                            <h1 className="text-xl font-semibold tracking-tight">
                                {meeting.title}
                            </h1>
                            <MeetingStatusBadge status={meeting.status} />
                        </div>
                        <p className="text-muted-foreground text-sm">
                            <Link
                                href={classrooms.show(classroom.uuid)}
                                className="hover:underline"
                            >
                                {classroom.name}
                            </Link>{' '}
                            <ClassroomStatusBadge status={classroom.status} />
                        </p>
                        <p className="text-muted-foreground text-sm">
                            Previsto: {formatDateTime(meeting.scheduled_at)} -{' '}
                            {formatDateTime(meeting.scheduled_end_at)
                                .split(', ')
                                .pop()}
                        </p>
                        <p className="text-muted-foreground text-sm">
                            Effettivo:{' '}
                            {meeting.started_at
                                ? formatDateTime(meeting.started_at)
                                : '—'}{' '}
                            -{' '}
                            {meeting.ended_at
                                ? formatDateTime(meeting.ended_at)
                                : '—'}
                        </p>
                        {meeting.bbb_internal_id && (
                            <p className="text-muted-foreground font-mono text-xs">
                                {meeting.bbb_internal_id}
                            </p>
                        )}
                    </div>

                    <div className="flex flex-wrap gap-2">
                        {meeting.status !== 'ended' &&
                            (meeting.status === 'running' ? (
                                <Button asChild>
                                    <a
                                        href={
                                            meetings.join({
                                                meeting: meeting.uuid,
                                            }).url
                                        }
                                    >
                                        Entra come moderatore
                                    </a>
                                </Button>
                            ) : (
                                <Button asChild>
                                    <a
                                        href={
                                            meetings.join({
                                                meeting: meeting.uuid,
                                            }).url
                                        }
                                    >
                                        Avvia ed entra
                                    </a>
                                </Button>
                            ))}

                        {meeting.status !== 'ended' && (
                            <Button variant="outline" onClick={refreshMeeting}>
                                Aggiorna stato
                            </Button>
                        )}

                        {meeting.status === 'running' && (
                            <ConfirmActionDialog
                                trigger={
                                    <Button variant="destructive">
                                        Termina
                                    </Button>
                                }
                                title="Terminare la lezione?"
                                description="I partecipanti verranno disconnessi e la lezione risulterà terminata."
                                confirmLabel="Termina"
                                destructive
                                onConfirm={endMeeting}
                            />
                        )}

                        <Button asChild variant="outline">
                            <a
                                href={
                                    meetings.attendance.export({
                                        meeting: meeting.uuid,
                                    }).url
                                }
                            >
                                Esporta presenze CSV
                            </a>
                        </Button>

                        {meeting.status === 'ended' &&
                            (formatempConfigured ? (
                                <>
                                    <Button
                                        onClick={syncFormatemp}
                                        disabled={
                                            !!meeting.formatemp_consolidated_at
                                        }
                                    >
                                        Invia presenze a Forma.Temp
                                    </Button>

                                    {!meeting.formatemp_consolidated_at &&
                                        !!meeting.formatemp_sent_at && (
                                            <ConfirmActionDialog
                                                trigger={
                                                    <Button variant="outline">
                                                        Consolida fascia
                                                    </Button>
                                                }
                                                title="Consolidare la fascia su Forma.Temp?"
                                                description="Il consolidamento è irreversibile: dopo averlo fatto il registro presenze di questa fascia non accetta altri invii."
                                                confirmLabel="Consolida"
                                                destructive
                                                onConfirm={consolidateFormatemp}
                                            />
                                        )}
                                </>
                            ) : (
                                <Tooltip>
                                    <TooltipTrigger asChild>
                                        <span>
                                            <Button disabled>
                                                Invia presenze a Forma.Temp
                                            </Button>
                                        </span>
                                    </TooltipTrigger>
                                    <TooltipContent>
                                        Configura Forma.Temp nelle impostazioni
                                        azienda.
                                    </TooltipContent>
                                </Tooltip>
                            ))}
                    </div>
                </div>

                {errors.formatemp && (
                    <p className="text-destructive text-sm">
                        {errors.formatemp}
                    </p>
                )}

                {meeting.status === 'ended' && formatempConfigured && (
                    <p className="text-muted-foreground text-sm">
                        Forma.Temp:{' '}
                        {meeting.formatemp_consolidated_at
                            ? `fascia consolidata il ${formatDateTime(meeting.formatemp_consolidated_at)}`
                            : meeting.formatemp_sent_at
                              ? `presenze inviate il ${formatDateTime(meeting.formatemp_sent_at)}, da consolidare`
                              : meeting.formatemp_fascia_id
                                ? 'lezione collegata a una fascia oraria, presenze non ancora inviate'
                                : 'lezione non ancora collegata a una fascia oraria'}
                    </p>
                )}

                {meeting.status === 'ended' && (
                    <MeetingReportCard
                        meetingUuid={meeting.uuid}
                        report={meeting.ai_report}
                    />
                )}

                <div className="space-y-2">
                    <h2 className="text-base font-medium">Registro presenze</h2>
                    <div className="rounded-xl border">
                        <Table>
                            <TableHeader>
                                <TableRow>
                                    <TableHead>Nome</TableHead>
                                    <TableHead>Cod. fiscale</TableHead>
                                    <TableHead>Ruolo</TableHead>
                                    <TableHead>Presenza totale</TableHead>
                                    <TableHead />
                                </TableRow>
                            </TableHeader>
                            <TableBody>
                                {participants.length === 0 && (
                                    <TableRow>
                                        <TableCell
                                            colSpan={5}
                                            className="text-muted-foreground h-24 text-center"
                                        >
                                            Nessuna presenza rilevata.
                                        </TableCell>
                                    </TableRow>
                                )}
                                {participants.map((participant) => (
                                    <Fragment key={participant.id}>
                                        <TableRow>
                                            <TableCell>
                                                {participant.full_name}
                                            </TableCell>
                                            <TableCell className="font-mono text-xs">
                                                {participant.fiscal_code ?? '—'}
                                            </TableCell>
                                            <TableCell>
                                                <ParticipantRoleBadge
                                                    role={participant.role}
                                                />
                                            </TableCell>
                                            <TableCell>
                                                {formatSeconds(
                                                    participant.seconds,
                                                )}
                                            </TableCell>
                                            <TableCell className="text-right">
                                                {participant.intervals.length >
                                                    0 && (
                                                    <Button
                                                        variant="ghost"
                                                        size="sm"
                                                        onClick={() =>
                                                            setExpanded(
                                                                expanded ===
                                                                    participant.id
                                                                    ? null
                                                                    : participant.id,
                                                            )
                                                        }
                                                    >
                                                        {expanded ===
                                                        participant.id
                                                            ? 'Nascondi'
                                                            : 'Dettaglio'}
                                                    </Button>
                                                )}
                                            </TableCell>
                                        </TableRow>
                                        {expanded === participant.id && (
                                            <TableRow
                                                key={`${participant.id}-detail`}
                                            >
                                                <TableCell colSpan={5}>
                                                    <div className="space-y-1 py-1">
                                                        {participant.intervals.map(
                                                            (interval) => (
                                                                <p
                                                                    key={
                                                                        interval.id
                                                                    }
                                                                    className="text-muted-foreground text-sm"
                                                                >
                                                                    {formatDateTime(
                                                                        interval.joined_at,
                                                                    )}{' '}
                                                                    →{' '}
                                                                    {interval.left_at
                                                                        ? formatDateTime(
                                                                              interval.left_at,
                                                                          )
                                                                        : 'in corso'}{' '}
                                                                    (
                                                                    {formatSeconds(
                                                                        interval.seconds,
                                                                    )}
                                                                    )
                                                                </p>
                                                            ),
                                                        )}
                                                    </div>
                                                </TableCell>
                                            </TableRow>
                                        )}
                                    </Fragment>
                                ))}
                            </TableBody>
                        </Table>
                    </div>
                </div>

                <div className="space-y-2">
                    <h2 className="text-base font-medium">
                        Eventi BigBlueButton
                    </h2>
                    <div className="rounded-xl border">
                        <Table>
                            <TableHeader>
                                <TableRow>
                                    <TableHead>Orario</TableHead>
                                    <TableHead>Evento</TableHead>
                                    <TableHead>Utente</TableHead>
                                </TableRow>
                            </TableHeader>
                            <TableBody>
                                {recentEvents.length === 0 && (
                                    <TableRow>
                                        <TableCell
                                            colSpan={3}
                                            className="text-muted-foreground h-24 text-center"
                                        >
                                            Nessun evento registrato.
                                        </TableCell>
                                    </TableRow>
                                )}
                                {recentEvents.map((event) => (
                                    <TableRow key={event.id}>
                                        <TableCell>
                                            {formatDateTime(event.occurred_at)}
                                        </TableCell>
                                        <TableCell>{event.event}</TableCell>
                                        <TableCell>
                                            {event.bbb_user_id ?? '—'}
                                        </TableCell>
                                    </TableRow>
                                ))}
                            </TableBody>
                        </Table>
                    </div>
                </div>
            </div>
        </>
    );
}

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