import { Head, router } from '@inertiajs/react';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Spinner } from '@/components/ui/spinner';
import { useState } from 'react';

type Meeting = {
    uuid: string;
    title: string;
};

type Me = {
    meeting: string;
    user: string;
    name: string;
    role: 'MODERATOR' | 'VIEWER';
};

type Attendee = {
    userId: string;
    fullName: string;
    role: string;
};

type Props = {
    meeting: Meeting;
    me: Me;
    attendees: Attendee[];
};

function getInitials(name: string): string {
    return name
        .split(' ')
        .map((n) => n[0])
        .join('')
        .toUpperCase()
        .slice(0, 2);
}

function getRoleColor(
    role: string,
): 'default' | 'secondary' | 'outline' | 'destructive' {
    if (role === 'MODERATOR' || role === 'moderator') {
        return 'default';
    }
    return 'secondary';
}

function getRoleLabel(role: string): string {
    if (role === 'MODERATOR' || role === 'moderator') {
        return 'Docente';
    }
    return 'Partecipante';
}

export default function BbbRoom({ meeting, me, attendees }: Props) {
    const [isLeavingRoom, setIsLeavingRoom] = useState(false);
    const [isEndingSession, setIsEndingSession] = useState(false);

    const handleLeaveRoom = async () => {
        setIsLeavingRoom(true);
        try {
            router.post('/dev/bbb/room/leave', me);
        } finally {
            setIsLeavingRoom(false);
        }
    };

    const handleEndSession = async () => {
        setIsEndingSession(true);
        try {
            router.post('/dev/bbb/room/end', {
                meeting: me.meeting,
            });
        } finally {
            setIsEndingSession(false);
        }
    };

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

    return (
        <>
            <Head title={`${meeting.title} - BigBlueButton`} />

            <div className="text-foreground flex min-h-screen flex-col bg-slate-900">
                {/* Header Banner */}
                <div className="border-b border-slate-700 bg-slate-800 px-4 py-3 shadow-lg">
                    <div className="flex max-w-full items-center justify-between gap-4">
                        <div className="flex flex-col gap-1">
                            <div className="text-xs font-semibold tracking-wide text-yellow-500">
                                Aula BigBlueButton simulata (BBB_DRIVER=fake)
                            </div>
                            <h1 className="text-xl font-bold text-white">
                                {meeting.title}
                            </h1>
                        </div>
                    </div>
                </div>

                {/* Main Content */}
                <div className="flex flex-1 flex-col gap-6 p-6">
                    {/* Attendees Grid */}
                    <div className="flex-1">
                        <h2 className="mb-4 text-lg font-semibold text-white">
                            Partecipanti ({attendees.length})
                        </h2>

                        <div className="grid grid-cols-2 gap-4 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5">
                            {attendees.map((attendee) => (
                                <div
                                    key={attendee.userId}
                                    className="flex flex-col items-center gap-2"
                                >
                                    {/* Avatar */}
                                    <div className="flex h-20 w-20 items-center justify-center rounded-lg bg-gradient-to-br from-blue-400 to-blue-600 text-lg font-bold text-white shadow-lg">
                                        {getInitials(attendee.fullName)}
                                    </div>

                                    {/* Name */}
                                    <div className="max-w-[120px] truncate text-center text-sm font-medium text-white">
                                        {attendee.fullName}
                                    </div>

                                    {/* Role Badge */}
                                    <Badge
                                        variant={getRoleColor(attendee.role)}
                                        className="text-xs"
                                    >
                                        {getRoleLabel(attendee.role)}
                                    </Badge>
                                </div>
                            ))}
                        </div>

                        {attendees.length === 0 && (
                            <div className="text-muted-foreground flex h-40 items-center justify-center">
                                Nessun partecipante connesso
                            </div>
                        )}
                    </div>

                    {/* Controls */}
                    <div className="flex flex-wrap justify-center gap-3 border-t border-slate-700 pt-6">
                        <Button
                            onClick={handleLeaveRoom}
                            disabled={isLeavingRoom}
                            variant="outline"
                        >
                            {isLeavingRoom && <Spinner />}
                            Esci dalla lezione
                        </Button>

                        {me.role === 'MODERATOR' && (
                            <Button
                                onClick={handleEndSession}
                                disabled={isEndingSession}
                                variant="destructive"
                            >
                                {isEndingSession && <Spinner />}
                                Termina lezione per tutti
                            </Button>
                        )}

                        <Button
                            onClick={handleRefreshAttendees}
                            variant="secondary"
                        >
                            Aggiorna partecipanti
                        </Button>
                    </div>
                </div>
            </div>
        </>
    );
}
