import { Head } from '@inertiajs/react';
import type { PaginationState } from '@/components/data-table';
import { DataTable } from '@/components/data-table';
import type { FilterField } from '@/components/filter-dialog';
import { FilterDialog } from '@/components/filter-dialog';
import { PageHeader } from '@/components/page-header';
import { useServerTable } from '@/hooks/use-server-table';
import { index } from '@/routes/admin/manage/course-registrations';
import type {
    CourseRegistrationRow,
    DepartmentSummary,
} from '@/types/course-registration';
import { createCourseRegistrationColumns } from './columns';

type Props = {
    departments: DepartmentSummary[];
    registrations: {
        data: CourseRegistrationRow[];
        current_page: number;
        last_page: number;
        per_page: number;
        total: number;
    };
    filters: {
        department_id?: string;
    };
};

export default function CourseRegistrationIndex({
    departments,
    registrations,
    filters,
}: Props) {
    const filterFields: FilterField[] = [
        {
            key: 'department_id',
            label: 'Jurusan',
            options: departments.map((department) => ({
                value: String(department.id),
                label: department.name,
            })),
        },
    ];

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

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

    const columns = createCourseRegistrationColumns();

    return (
        <>
            <Head title="Registrasi KRS" />

            <div className="flex h-full flex-1 flex-col gap-6 overflow-x-auto p-4 md:p-6">
                <PageHeader title="Registrasi KRS" />

                <DataTable
                    columns={columns}
                    data={registrations.data}
                    pagination={pagination}
                    onPageChange={handlePageChange}
                    onPerPageChange={handlePerPageChange}
                    onSearchChange={handleSearchChange}
                    searchValue={search}
                    searchKey="student"
                    groupBy={(row) =>
                        row.student?.department?.name ?? 'Tanpa Jurusan'
                    }
                    toolbar={
                        <FilterDialog
                            fields={filterFields}
                            activeFilters={filters}
                            onApply={applyFilters}
                        />
                    }
                />
            </div>
        </>
    );
}
