import { Head, usePage, router } from '@inertiajs/react';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
    Card,
    CardContent,
    CardDescription,
    CardHeader,
    CardTitle,
} from '@/components/ui/card';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import AppLogoIcon from '@/components/app-logo-icon';

type Participant = {
    id: string;
    first_name: string;
    last_name: string;
    full_name: string;
    role: 'learner' | 'trainer';
};

type Classroom = {
    name: string;
    course_title: string;
    code: string;
};

type Meeting = {
    uuid: string;
    title: string;
    scheduled_at: string;
    scheduled_end_at: string;
    status: 'scheduled' | 'running' | 'ended';
    joinable: boolean;
    window_open: boolean;
    enter_url: string;
};

type Props = {
    participant: Participant;
    classroom: Classroom;
    meetings: Meeting[];
    token: string;
};

function formatDateTime(dateString: string) {
    return new Intl.DateTimeFormat('it-IT', {
        dateStyle: 'medium',
        timeStyle: 'short',
    }).format(new Date(dateString));
}

function getStatusBadge(status: Meeting['status']) {
    switch (status) {
        case 'scheduled':
            return <Badge variant="outline">Pianificata</Badge>;
        case 'running':
            return <Badge variant="default">In corso</Badge>;
        case 'ended':
            return <Badge variant="secondary">Terminata</Badge>;
    }
}

export default function JoinShow({ participant, classroom, meetings }: Props) {
    const { errors } = usePage().props;

    const handleRefresh = () => {
        router.reload();
    };

    return (
        <>
            <Head title={`${participant.full_name} - EasyForma`} />

            <div className="bg-background flex min-h-screen flex-col items-center justify-center gap-6 p-6 md:p-10">
                <div className="flex w-full max-w-4xl flex-col gap-6">
                    {/* Header with Logo */}
                    <div className="flex items-center gap-2 self-center">
                        <div className="flex h-9 w-9 items-center justify-center">
                            <AppLogoIcon className="text-foreground size-9 fill-current" />
                        </div>
                    </div>

                    {/* Main Card */}
                    <Card>
                        <CardHeader>
                            <CardTitle className="text-2xl">
                                Ciao {participant.full_name}
                            </CardTitle>
                            <CardDescription>
                                {classroom.name} - {classroom.course_title}
                            </CardDescription>
                        </CardHeader>

                        <CardContent className="space-y-6">
                            {/* Error Alert */}
                            {errors.meeting && (
                                <Alert variant="destructive">
                                    <AlertDescription>
                                        {errors.meeting}
                                    </AlertDescription>
                                </Alert>
                            )}

                            {/* Info Message */}
                            <div className="text-muted-foreground bg-muted rounded-lg border p-4 text-sm">
                                <p>
                                    La tua presenza è tracciata in base agli
                                    orari di accesso e uscita dalla lezione.
                                    Puoi aggiornare questa pagina in qualsiasi
                                    momento per verificare i nuovi corsi.
                                </p>
                            </div>

                            {/* Meetings Table */}
                            <div className="overflow-x-auto">
                                <Table>
                                    <TableHeader>
                                        <TableRow>
                                            <TableHead>Lezione</TableHead>
                                            <TableHead>Data e Ora</TableHead>
                                            <TableHead>Stato</TableHead>
                                            <TableHead className="text-right">
                                                Azione
                                            </TableHead>
                                        </TableRow>
                                    </TableHeader>
                                    <TableBody>
                                        {meetings.length > 0 ? (
                                            meetings.map((meeting) => (
                                                <TableRow key={meeting.uuid}>
                                                    <TableCell className="font-medium">
                                                        {meeting.title}
                                                    </TableCell>
                                                    <TableCell>
                                                        {formatDateTime(
                                                            meeting.scheduled_at,
                                                        )}{' '}
                                                        -{' '}
                                                        {formatDateTime(
                                                            meeting.scheduled_end_at,
                                                        )}
                                                    </TableCell>
                                                    <TableCell>
                                                        {getStatusBadge(
                                                            meeting.status,
                                                        )}
                                                    </TableCell>
                                                    <TableCell className="text-right">
                                                        {meeting.joinable ? (
                                                            <Button
                                                                asChild
                                                                size="sm"
                                                            >
                                                                <a
                                                                    href={
                                                                        meeting.enter_url
                                                                    }
                                                                >
                                                                    Entra in
                                                                    aula
                                                                </a>
                                                            </Button>
                                                        ) : (
                                                            <div className="text-muted-foreground text-xs">
                                                                {meeting.status ===
                                                                'scheduled' ? (
                                                                    meeting.window_open ? (
                                                                        'In attesa che il docente avvii la lezione'
                                                                    ) : (
                                                                        <>
                                                                            Disponibile
                                                                            dalle{' '}
                                                                            {formatDateTime(
                                                                                meeting.scheduled_at,
                                                                            )}
                                                                        </>
                                                                    )
                                                                ) : (
                                                                    'Non disponibile'
                                                                )}
                                                            </div>
                                                        )}
                                                    </TableCell>
                                                </TableRow>
                                            ))
                                        ) : (
                                            <TableRow>
                                                <TableCell
                                                    colSpan={4}
                                                    className="text-muted-foreground py-8 text-center"
                                                >
                                                    Nessuna lezione disponibile
                                                </TableCell>
                                            </TableRow>
                                        )}
                                    </TableBody>
                                </Table>
                            </div>

                            {/* Refresh Button */}
                            <div className="flex justify-center">
                                <Button
                                    onClick={handleRefresh}
                                    variant="outline"
                                >
                                    Aggiorna
                                </Button>
                            </div>
                        </CardContent>
                    </Card>
                </div>
            </div>
        </>
    );
}
