import { Head, Link, router } from '@inertiajs/react';
import type { ColumnDef } from '@tanstack/react-table';
import { format } from 'date-fns';
import { ArrowLeft, Trash2 } from 'lucide-react';
import { useState } from 'react';
import { DataTable } from '@/components/data-table';
import { DeleteConfirmDialog } from '@/components/delete-confirm-dialog';
import { PageHeader } from '@/components/page-header';
import { RowActions } from '@/components/row-actions';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { usePermissions } from '@/hooks/use-permissions';
import { index as courseClassIndex } from '@/routes/admin/manage/course-classes';
import { destroy } from '@/routes/admin/manage/course-classes/enrollments';
import { formatAcademicTermLabel } from '@/types/academic-term';
import type { ClassEnrollment } from '@/types/class-enrollment';
import type { CourseClass } from '@/types/course-class';
import { ClassMethodLabels } from '@/types/course-class';

type Props = {
    courseClass: CourseClass;
    enrollments: ClassEnrollment[];
};

export default function ClassEnrollmentIndex({
    courseClass,
    enrollments,
}: Props) {
    const [deleting, setDeleting] = useState<ClassEnrollment | null>(null);
    const { hasPermission } = usePermissions();
    const canDelete = hasPermission('delete-course-class-enrollments');

    function handleDelete() {
        if (!deleting) {
            return;
        }

        router.delete(destroy([courseClass.id, deleting.id]), {
            onSuccess: () => setDeleting(null),
        });
    }

    const columns: ColumnDef<ClassEnrollment>[] = [
        {
            accessorKey: 'student.student_number',
            header: () => <span>NIM</span>,
            cell: ({ row }) => row.original.student?.student_number ?? '-',
        },
        {
            accessorKey: 'student.user.profile.full_name',
            header: () => <span>Nama Mahasiswa</span>,
            cell: ({ row }) =>
                row.original.student?.user?.profile?.full_name ?? '-',
        },
        {
            accessorKey: 'student.department.name',
            header: () => <span>Jurusan</span>,
            cell: ({ row }) => row.original.student?.department?.name ?? '-',
        },
        {
            accessorKey: 'enrolled_at',
            header: () => <span>Tanggal Daftar</span>,
            cell: ({ row }) => {
                const enrolledAt = row.getValue('enrolled_at') as string | null;

                return enrolledAt
                    ? format(new Date(enrolledAt), 'd MMM yyyy')
                    : '-';
            },
        },
    ];

    if (canDelete) {
        columns.push({
            id: 'actions',
            header: () => <span className="block text-center">Aksi</span>,
            meta: {
                className: 'w-[80px] text-center',
                headerClassName: 'w-[80px] text-center',
            },
            cell: ({ row }) => (
                <RowActions
                    actions={[
                        {
                            label: 'Keluarkan',
                            icon: (
                                <Trash2 className="h-4 w-4 text-destructive" />
                            ),
                            show: canDelete,
                            onClick: () => setDeleting(row.original),
                        },
                    ]}
                />
            ),
        });
    }

    return (
        <>
            <Head title="Peserta Kelas" />

            <div className="flex h-full flex-1 flex-col gap-6 overflow-x-auto p-4 md:p-6">
                <PageHeader
                    title="Peserta Kelas"
                    actions={
                        <Button variant="outline" asChild>
                            <Link href={courseClassIndex.url()}>
                                <ArrowLeft className="h-4 w-4" />
                                Kembali
                            </Link>
                        </Button>
                    }
                />

                <Card>
                    <CardHeader>
                        <CardTitle>Detail Kelas Mata Kuliah</CardTitle>
                    </CardHeader>
                    <CardContent className="grid gap-1 text-sm text-muted-foreground">
                        <p>
                            Mata Kuliah: {courseClass.course?.code} -{' '}
                            {courseClass.course?.name}
                        </p>
                        <p>
                            Dosen Pengampu:{' '}
                            {courseClass.lecturer?.user?.profile?.full_name ??
                                '-'}
                        </p>
                        <p>
                            Periode:{' '}
                            {courseClass.academic_term
                                ? formatAcademicTermLabel(
                                      courseClass.academic_term,
                                  )
                                : '-'}
                        </p>
                        <p>
                            Metode:{' '}
                            {courseClass.method
                                ? ClassMethodLabels[courseClass.method]
                                : '-'}
                        </p>
                        <p>Jumlah Peserta: {enrollments.length}</p>
                    </CardContent>
                </Card>

                <h2 className="text-lg font-semibold">Daftar Mahasiswa</h2>

                <DataTable columns={columns} data={enrollments} />

                <DeleteConfirmDialog
                    target={deleting}
                    onOpenChange={(open) => {
                        if (!open) {
                            setDeleting(null);
                        }
                    }}
                    title="Keluarkan Mahasiswa"
                    description={(enrollment) =>
                        `Apakah Anda yakin ingin mengeluarkan "${enrollment.student?.user?.profile?.full_name ?? 'mahasiswa ini'}" dari kelas ini?`
                    }
                    onConfirm={handleDelete}
                />
            </div>
        </>
    );
}
