import { Head, Link, router } from '@inertiajs/react';
import { FileSpreadsheet, 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 { Button } from '@/components/ui/button';
import { useServerTable } from '@/hooks/use-server-table';
import {
    index as lecturersIndex,
    create,
    edit,
    destroy,
    reset_password,
    update_user_status,
    exportMethod as exportLecturers,
} from '@/routes/admin/users/lecturers';
import { formatDepartmentLabel } from '@/types/department';
import type { Lecturer } from './columns';
import { createLecturerColumns } from './columns';

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

type Props = {
    lecturers: {
        data: Lecturer[];
        current_page: number;
        last_page: number;
        per_page: number;
        total: number;
    };
    departments: Department[];
    filters: {
        gender?: string;
        department_id?: string;
    };
};

export default function LecturerIndex({
    lecturers,
    departments,
    filters,
}: Props) {
    const [deleting, setDeleting] = useState<Lecturer | null>(null);
    const [resetting, setResetting] = useState<Lecturer | null>(null);

    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),
            })),
        },
    ];

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

    const {
        search,
        handlePageChange,
        handlePerPageChange,
        handleSearchChange,
        applyFilters,
    } = useServerTable({
        route: () => lecturersIndex.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 handleUserStatusChange(lecturer: Lecturer, isActive: boolean) {
        router.patch(
            update_user_status.url(lecturer.id),
            { is_active: isActive },
            { preserveScroll: true },
        );
    }

    const columns = createLecturerColumns({
        handleEdit: (lecturer) => {
            router.get(edit.url(lecturer.id));
        },
        handleDeleteClick: (lecturer) => setDeleting(lecturer),
        handleResetPassword: (lecturer) => setResetting(lecturer),
        handleUserStatusChange,
    });

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

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

                <DataTable
                    columns={columns}
                    data={lecturers.data}
                    searchKey="name"
                    searchPlaceholder="Cari dosen..."
                    emptyText="Belum ada data dosen."
                    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 Dosen"
                    description={(lecturer) =>
                        `Apakah Anda yakin ingin menghapus dosen "${lecturer.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 dosen "${resetting.profile?.full_name}" ke kata sandi default?`
                            : ''
                    }
                    confirmLabel="Reset"
                    confirmIcon={<RotateCcw className="h-4 w-4" />}
                    variant="default"
                    onConfirm={handleResetPassword}
                />
            </div>
        </>
    );
}
