import { Form, Head, router } from '@inertiajs/react';
import { Calendar, Clock, ExternalLink, Trash2, Users, Video } from 'lucide-react';
import { Button } from '@/components/ui/button';
import AppLayout from '@/layouts/app-layout';
import type { BreadcrumbItem } from '@/types';

type Registrant = { id: number; name: string; email: string };
type LiveClass = {
    id: number;
    title: string;
    description: string | null;
    scheduled_at: string;
    duration_minutes: number;
    meeting_url: string;
    recording_url: string | null;
    is_published: boolean;
    course: { id: number; title: string; slug: string } | null;
    registrants: Registrant[];
};

type Props = { liveClass: LiveClass };

const breadcrumbs: BreadcrumbItem[] = [
    { title: 'Live Class Saya', href: '/instructor/live-classes' },
    { title: 'Detail', href: '#' },
];

function formatSchedule(dateStr: string) {
    const d = new Date(dateStr);
    return d.toLocaleDateString('id-ID', { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' }) +
        ' pukul ' + d.toLocaleTimeString('id-ID', { hour: '2-digit', minute: '2-digit' }) + ' WIB';
}

export default function InstructorLiveClassShow({ liveClass }: Props) {
    const isPast = new Date(liveClass.scheduled_at) < new Date();

    function deleteLiveClass() {
        if (confirm(`Hapus live class "${liveClass.title}"?`)) {
            router.delete(`/instructor/live-classes/${liveClass.id}`);
        }
    }

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

            <div className="flex flex-col gap-6 p-4 md:p-6 max-w-2xl">
                {/* Header */}
                <div className="flex items-start justify-between gap-4">
                    <div>
                        <div className="flex items-center gap-2 flex-wrap">
                            <h1 className="text-xl font-bold">{liveClass.title}</h1>
                            <span className={`rounded-full px-2.5 py-0.5 text-xs font-medium ${liveClass.is_published ? 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400' : 'bg-muted text-muted-foreground'}`}>
                                {liveClass.is_published ? 'Published' : 'Draft'}
                            </span>
                        </div>
                        <p className="mt-0.5 text-sm text-muted-foreground">{formatSchedule(liveClass.scheduled_at)}</p>
                    </div>
                    <Button size="sm" variant="destructive" onClick={deleteLiveClass}>
                        <Trash2 className="h-4 w-4" />
                    </Button>
                </div>

                {/* Quick links */}
                <div className="flex gap-3">
                    <Button asChild size="sm" variant="secondary">
                        <a href={liveClass.meeting_url} target="_blank" rel="noopener noreferrer">
                            <ExternalLink className="mr-1.5 h-4 w-4" />
                            Buka Meeting Link
                        </a>
                    </Button>
                    {liveClass.recording_url && (
                        <Button asChild size="sm" variant="secondary">
                            <a href={liveClass.recording_url} target="_blank" rel="noopener noreferrer">
                                <Video className="mr-1.5 h-4 w-4" />
                                Rekaman
                            </a>
                        </Button>
                    )}
                </div>

                {/* Edit form */}
                <Form action={`/instructor/live-classes/${liveClass.id}`} method="patch" className="rounded-xl border bg-card p-5">
                    {({ errors, processing, wasSuccessful }) => (
                        <div className="flex flex-col gap-4">
                            <p className="text-sm font-medium">Edit Live Class</p>

                            <div>
                                <label className="mb-1.5 block text-xs text-muted-foreground">Judul</label>
                                <input
                                    name="title"
                                    defaultValue={liveClass.title}
                                    className="border-input focus-visible:border-ring w-full rounded-md border bg-transparent px-3 py-2 text-sm outline-none"
                                />
                            </div>

                            <div>
                                <label className="mb-1.5 block text-xs text-muted-foreground">Deskripsi</label>
                                <textarea
                                    name="description"
                                    rows={2}
                                    defaultValue={liveClass.description ?? ''}
                                    className="border-input focus-visible:border-ring w-full rounded-md border bg-transparent px-3 py-2 text-sm outline-none"
                                />
                            </div>

                            <div className="grid grid-cols-2 gap-3">
                                <div>
                                    <label className="mb-1.5 block text-xs text-muted-foreground">Tanggal & Waktu</label>
                                    <input
                                        name="scheduled_at"
                                        type="datetime-local"
                                        defaultValue={liveClass.scheduled_at.slice(0, 16)}
                                        className="border-input focus-visible:border-ring w-full rounded-md border bg-transparent px-3 py-2 text-sm outline-none"
                                    />
                                </div>
                                <div>
                                    <label className="mb-1.5 block text-xs text-muted-foreground">Durasi (menit)</label>
                                    <input
                                        name="duration_minutes"
                                        type="number"
                                        defaultValue={liveClass.duration_minutes}
                                        className="border-input focus-visible:border-ring w-full rounded-md border bg-transparent px-3 py-2 text-sm outline-none"
                                    />
                                </div>
                            </div>

                            <div>
                                <label className="mb-1.5 block text-xs text-muted-foreground">Meeting Link</label>
                                <input
                                    name="meeting_url"
                                    type="url"
                                    defaultValue={liveClass.meeting_url}
                                    className="border-input focus-visible:border-ring w-full rounded-md border bg-transparent px-3 py-2 text-sm outline-none"
                                />
                                {errors.meeting_url && <p className="mt-1 text-xs text-destructive">{errors.meeting_url}</p>}
                            </div>

                            <div>
                                <label className="mb-1.5 block text-xs text-muted-foreground">Link Rekaman (opsional)</label>
                                <input
                                    name="recording_url"
                                    type="url"
                                    defaultValue={liveClass.recording_url ?? ''}
                                    className="border-input focus-visible:border-ring w-full rounded-md border bg-transparent px-3 py-2 text-sm outline-none"
                                    placeholder="https://youtube.com/... (isi setelah sesi selesai)"
                                />
                            </div>

                            <div className="flex items-center gap-2">
                                <input
                                    type="checkbox"
                                    name="is_published"
                                    id="is_published_edit"
                                    value="1"
                                    defaultChecked={liveClass.is_published}
                                    className="h-4 w-4 rounded border"
                                />
                                <label htmlFor="is_published_edit" className="text-sm">Published</label>
                            </div>

                            <div className="flex items-center gap-3">
                                <Button type="submit" size="sm" disabled={processing}>Simpan</Button>
                                {wasSuccessful && <p className="text-xs text-green-600">Tersimpan!</p>}
                            </div>
                        </div>
                    )}
                </Form>

                {/* Registrants */}
                <div className="rounded-xl border bg-card">
                    <div className="flex items-center gap-2 border-b px-4 py-3">
                        <Users className="h-4 w-4 text-muted-foreground" />
                        <p className="font-medium text-sm">Peserta Terdaftar ({liveClass.registrants.length})</p>
                    </div>

                    {liveClass.registrants.length === 0 ? (
                        <p className="p-4 text-sm text-muted-foreground">Belum ada peserta yang mendaftar.</p>
                    ) : (
                        <div className="divide-y">
                            {liveClass.registrants.map((r) => (
                                <div key={r.id} className="flex items-center gap-3 px-4 py-2.5">
                                    <div className="flex h-7 w-7 items-center justify-center rounded-full bg-primary/10 text-xs font-medium text-primary">
                                        {r.name.charAt(0).toUpperCase()}
                                    </div>
                                    <div>
                                        <p className="text-sm font-medium">{r.name}</p>
                                        <p className="text-xs text-muted-foreground">{r.email}</p>
                                    </div>
                                </div>
                            ))}
                        </div>
                    )}
                </div>
            </div>
        </>
    );
}

InstructorLiveClassShow.layout = (page: React.ReactNode) => (
    <AppLayout breadcrumbs={breadcrumbs}>{page}</AppLayout>
);
