import { Head, Link, router } from '@inertiajs/react';
import { FileSpreadsheet, Info, Plus, RotateCcw } from 'lucide-react';
import { useState } from 'react';
import { ConfirmDialog } from '@/components/confirm-dialog';
import type { PaginationState } from '@/components/data-table';
import { DataTable } from '@/components/data-table';
import { DeleteConfirmDialog } from '@/components/delete-confirm-dialog';
import type { FilterField } from '@/components/filter-dialog';
import { FilterDialog } from '@/components/filter-dialog';
import { PageHeader } from '@/components/page-header';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { Button } from '@/components/ui/button';
import { usePermissions } from '@/hooks/use-permissions';
import { useServerTable } from '@/hooks/use-server-table';
import {
    create,
    destroy,
    edit,
    reset_password,
    update_status,
    update_user_status,
    exportMethod as exportStudents,
    index as studentsIndex,
} from '@/routes/admin/users/students';
import { formatDepartmentLabel } from '@/types/department';
import { createStudentColumns } from './columns';
import type { Student } from './columns';

type Department = { id: number; name: string; degree_level: string | null };
type StatusOption = { value: string; label: string };

type Props = {
    students: {
        data: Student[];
        current_page: number;
        last_page: number;
        per_page: number;
        total: number;
    };
    departments: Department[];
    statuses: StatusOption[];
    enrollmentYears: number[];
    filters: {
        gender?: string;
        department_id?: string;
        status?: string;
        enrollment_year?: string;
    };
};

export default function StudentIndex({
    students,
    departments,
    statuses,
    enrollmentYears,
    filters,
}: Props) {
    const [deleting, setDeleting] = useState<Student | null>(null);
    const [resetting, setResetting] = useState<Student | null>(null);
    const { hasPermission } = usePermissions();
    const canCreate = hasPermission('create-students');
    const canUpdate = hasPermission('update-students');
    const canDelete = hasPermission('delete-students');
    const canResetPassword = hasPermission('reset-students-password');
    const canUpdateAcademicStatus = hasPermission(
        'update-students-academic-status',
    );
    const canUpdateAccountStatus = hasPermission(
        'update-students-account-status',
    );
    const canExport = hasPermission('export-students');

    const filterFields: FilterField[] = [
        {
            key: 'gender',
            label: 'Jenis Kelamin',
            options: [
                { value: 'male', label: 'Laki-laki' },
                { value: 'female', label: 'Perempuan' },
            ],
        },
        {
            key: 'department_id',
            label: 'Jurusan',
            options: departments.map((department) => ({
                value: String(department.id),
                label: formatDepartmentLabel(department),
            })),
        },
        {
            key: 'status',
            label: 'Status',
            options: statuses,
        },
        {
            key: 'enrollment_year',
            label: 'Angkatan',
            options: enrollmentYears.map((year) => ({
                value: String(year),
                label: String(year),
            })),
        },
    ];

    const pagination: PaginationState = {
        current_page: students.current_page,
        last_page: students.last_page,
        per_page: students.per_page,
        total: students.total,
    };

    const {
        search,
        handlePageChange,
        handlePerPageChange,
        handleSearchChange,
        applyFilters,
    } = useServerTable({
        route: () => studentsIndex.url(),
        pagination,
        filters,
    });

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

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

    function handleResetPassword() {
        if (!resetting) {
            return;
        }

        router.patch(
            reset_password.url(resetting.id),
            {},
            {
                onSuccess: () => setResetting(null),
            },
        );
    }

    function handleStatusChange(student: Student, status: string) {
        router.patch(
            update_status.url(student.id),
            { status },
            { preserveScroll: true },
        );
    }

    function handleUserStatusChange(student: Student, isActive: boolean) {
        router.patch(
            update_user_status.url(student.id),
            { is_active: isActive },
            { preserveScroll: true },
        );
    }

    const columns = createStudentColumns({
        handleEdit: (student) => {
            router.get(edit.url(student.id));
        },
        handleDeleteClick: (student) => setDeleting(student),
        handleResetPassword: (student) => setResetting(student),
        handleStatusChange,
        handleUserStatusChange,
        statuses,
        canUpdate,
        canDelete,
        canResetPassword,
        canUpdateAcademicStatus,
        canUpdateAccountStatus,
    });

    return (
        <>
            <Head title="Mahasiswa" />

            <div className="flex h-full flex-1 flex-col gap-6 overflow-x-auto p-4 md:p-6">
                <PageHeader
                    title="Mahasiswa"
                    actions={
                        <div className="flex items-center gap-2">
                            {canExport && (
                                <Button variant="outline" asChild>
                                    <a
                                        href={exportStudents.url({
                                            query: { search, ...filters },
                                        })}
                                    >
                                        <FileSpreadsheet className="h-4 w-4" />
                                        Export
                                    </a>
                                </Button>
                            )}
                            {canCreate && (
                                <Button asChild>
                                    <Link href={create.url()}>
                                        <Plus className="h-4 w-4" />
                                        Tambah
                                    </Link>
                                </Button>
                            )}
                        </div>
                    }
                />

                <Alert>
                    <Info />
                    <AlertTitle>Ubah status mahasiswa</AlertTitle>
                    <AlertDescription>
                        Klik badge Status pada tabel untuk mengubah status
                        mahasiswa secara langsung.
                    </AlertDescription>
                </Alert>

                <DataTable
                    columns={columns}
                    data={students.data}
                    searchKey="name"
                    pagination={pagination}
                    onPageChange={handlePageChange}
                    onPerPageChange={handlePerPageChange}
                    onSearchChange={handleSearchChange}
                    searchValue={search}
                    toolbar={
                        <FilterDialog
                            fields={filterFields}
                            activeFilters={filters}
                            onApply={applyFilters}
                        />
                    }
                />

                <DeleteConfirmDialog
                    target={deleting}
                    onOpenChange={(open) => {
                        if (!open) {
                            setDeleting(null);
                        }
                    }}
                    title="Hapus Mahasiswa"
                    description={(student) =>
                        `Apakah Anda yakin ingin menghapus mahasiswa "${student.profile?.full_name}"? Tindakan ini tidak dapat dibatalkan.`
                    }
                    onConfirm={handleDelete}
                />

                <ConfirmDialog
                    open={resetting !== null}
                    onOpenChange={(open) => {
                        if (!open) {
                            setResetting(null);
                        }
                    }}
                    title="Reset Kata Sandi"
                    description={
                        resetting
                            ? `Apakah Anda yakin ingin mereset kata sandi mahasiswa "${resetting.profile?.full_name}" ke kata sandi default?`
                            : ''
                    }
                    confirmLabel="Reset"
                    confirmIcon={<RotateCcw className="h-4 w-4" />}
                    variant="default"
                    onConfirm={handleResetPassword}
                />
            </div>
        </>
    );
}
