import { router } from '@inertiajs/react';
import { RefreshCwIcon } from 'lucide-react';
import { useCallback, useEffect, useState } from 'react';
import ConfirmActionDialog from '@/components/classrooms/confirm-action-dialog';
import { formatDateTime } from '@/components/classrooms/format';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { Button } from '@/components/ui/button';
import { Spinner } from '@/components/ui/spinner';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import recordings from '@/routes/classrooms/recordings';

export type Recording = {
    record_id: string;
    meeting_id: string;
    internal_meeting_id: string;
    name: string;
    published: boolean;
    state: string;
    started_at: number | null;
    ended_at: number | null;
    playback_url: string | null;
};

type Props = {
    classroomUuid: string;
};

/**
 * Recordings are not stored locally: the list is read from BigBlueButton on demand.
 * Deletion goes through the Inertia router so the flash toast is shown as everywhere else.
 */
export default function RecordingsCard({ classroomUuid }: Props) {
    const [items, setItems] = useState<Recording[]>([]);
    const [loading, setLoading] = useState(true);
    const [failed, setFailed] = useState(false);

    const load = useCallback(() => {
        setLoading(true);
        setFailed(false);

        fetch(recordings.index(classroomUuid).url, {
            headers: { Accept: 'application/json' },
        })
            .then((response) => {
                if (!response.ok) {
                    throw new Error('request failed');
                }

                return response.json() as Promise<{ recordings: Recording[] }>;
            })
            .then((data) => setItems(data.recordings))
            .catch(() => setFailed(true))
            .finally(() => setLoading(false));
    }, [classroomUuid]);

    useEffect(() => load(), [load]);

    function remove(recording: Recording) {
        router.delete(
            recordings.destroy({
                classroom: classroomUuid,
                recordId: recording.record_id,
            }).url,
            { preserveScroll: true, onSuccess: () => load() },
        );
    }

    return (
        <div className="space-y-4 rounded-xl border p-4">
            <div className="flex flex-wrap items-center justify-between gap-3">
                <div className="space-y-0.5">
                    <h2 className="font-semibold">Registrazioni</h2>
                    <p className="text-muted-foreground text-sm">
                        Le registrazioni restano disponibili sul server
                        BigBlueButton e vengono eliminate automaticamente dopo
                        il periodo di conservazione configurato.
                    </p>
                </div>
                <Button variant="outline" size="sm" onClick={() => load()}>
                    <RefreshCwIcon />
                    Aggiorna
                </Button>
            </div>

            {failed && (
                <Alert variant="destructive">
                    <AlertTitle>Registrazioni non disponibili</AlertTitle>
                    <AlertDescription>
                        Non è stato possibile contattare il server
                        BigBlueButton.
                    </AlertDescription>
                </Alert>
            )}

            {loading ? (
                <div className="text-muted-foreground flex items-center gap-2 py-6 text-sm">
                    <Spinner />
                    Caricamento delle registrazioni…
                </div>
            ) : (
                <Table>
                    <TableHeader>
                        <TableRow>
                            <TableHead>Nome</TableHead>
                            <TableHead>Data</TableHead>
                            <TableHead className="text-right">Azioni</TableHead>
                        </TableRow>
                    </TableHeader>
                    <TableBody>
                        {items.length === 0 && (
                            <TableRow>
                                <TableCell
                                    colSpan={3}
                                    className="text-muted-foreground h-24 text-center"
                                >
                                    Nessuna registrazione disponibile.
                                </TableCell>
                            </TableRow>
                        )}
                        {items.map((recording) => (
                            <TableRow key={recording.record_id}>
                                <TableCell>{recording.name}</TableCell>
                                <TableCell>
                                    {recording.started_at
                                        ? formatDateTime(
                                              new Date(
                                                  recording.started_at * 1000,
                                              ).toISOString(),
                                          )
                                        : '—'}
                                </TableCell>
                                <TableCell className="text-right">
                                    <div className="flex justify-end gap-1">
                                        {recording.playback_url && (
                                            <Button
                                                asChild
                                                variant="ghost"
                                                size="sm"
                                            >
                                                <a
                                                    href={
                                                        recording.playback_url
                                                    }
                                                    target="_blank"
                                                    rel="noreferrer"
                                                >
                                                    Guarda
                                                </a>
                                            </Button>
                                        )}
                                        <ConfirmActionDialog
                                            trigger={
                                                <Button
                                                    variant="ghost"
                                                    size="sm"
                                                    className="text-destructive"
                                                >
                                                    Elimina
                                                </Button>
                                            }
                                            title="Eliminare la registrazione?"
                                            description={`La registrazione "${recording.name}" verrà rimossa definitivamente dal server BigBlueButton.`}
                                            confirmLabel="Elimina"
                                            destructive
                                            onConfirm={() => remove(recording)}
                                        />
                                    </div>
                                </TableCell>
                            </TableRow>
                        ))}
                    </TableBody>
                </Table>
            )}
        </div>
    );
}
