import { Head, router } from '@inertiajs/react';
import { Plus } from 'lucide-react';
import { useState } from 'react';
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 { FormDialog } from '@/components/form-dialog';
import InputError from '@/components/input-error';
import { PageHeader } from '@/components/page-header';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { useServerTable } from '@/hooks/use-server-table';
import {
    index as courseRegistrationIndex,
    destroy,
    store,
    update,
} from '@/routes/admin/manage/course-registrations';
import type {
    CourseRegistration,
    CourseRegistrationCourseClass,
    CourseRegistrationStudent,
} from '@/types/course-registration';
import {
    RegistrationStatuses,
    RegistrationStatusLabels,
} from '@/types/course-registration';
import { createCourseRegistrationColumns } from './columns';

type AcademicTermOption = { id: number; name: string; semester: string };
type LecturerOption = {
    id: number;
    lecturer_number: string;
    user: { profile: { full_name: string } | null } | null;
};

type Props = {
    registrations: {
        data: CourseRegistration[];
        current_page: number;
        last_page: number;
        per_page: number;
        total: number;
    };
    students: CourseRegistrationStudent[];
    academicTerms: AcademicTermOption[];
    courseClasses: CourseRegistrationCourseClass[];
    lecturers: LecturerOption[];
    highlight?: number;
    filters: {
        status?: string;
        academic_term_id?: string;
    };
};

function studentLabel(student: CourseRegistrationStudent): string {
    return `${student.user?.profile?.full_name ?? 'N/A'} - ${student.student_number}`;
}

function courseClassLabel(courseClass: CourseRegistrationCourseClass): string {
    const course = courseClass.course;

    return `${course?.code ?? '-'} - ${course?.name ?? 'N/A'}`;
}

function lecturerLabel(lecturer: LecturerOption): string {
    return `${lecturer.user?.profile?.full_name ?? 'N/A'} - ${lecturer.lecturer_number}`;
}

export default function CourseRegistrationIndex({
    registrations,
    students,
    academicTerms,
    courseClasses,
    lecturers,
    highlight,
    filters,
}: Props) {
    const [createOpen, setCreateOpen] = useState(false);
    const [editing, setEditing] = useState<CourseRegistration | null>(null);
    const [deleting, setDeleting] = useState<CourseRegistration | null>(null);

    const filterFields: FilterField[] = [
        {
            key: 'status',
            label: 'Status',
            options: RegistrationStatuses.map((status) => ({
                value: status,
                label: RegistrationStatusLabels[status],
            })),
        },
        {
            key: 'academic_term_id',
            label: 'Periode Akademik',
            options: academicTerms.map((term) => ({
                value: String(term.id),
                label: term.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: () => courseRegistrationIndex.url(),
        pagination,
        filters,
    });

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

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

    const columns = createCourseRegistrationColumns({
        handleEdit: (registration) => setEditing(registration),
        handleDeleteClick: (registration) => setDeleting(registration),
    });

    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"
                    description={
                        highlight && (
                            <p className="mt-1 text-sm text-muted-foreground">
                                Menampilkan registrasi dari notifikasi.
                            </p>
                        )
                    }
                    actions={
                        <Button asChild>
                            <button
                                type="button"
                                onClick={() => setCreateOpen(true)}
                            >
                                <Plus className="h-4 w-4" />
                                Tambah
                            </button>
                        </Button>
                    }
                />

                <CreateForm
                    open={createOpen}
                    onOpenChange={setCreateOpen}
                    students={students}
                    academicTerms={academicTerms}
                    courseClasses={courseClasses}
                    lecturers={lecturers}
                />

                <EditForm
                    key={editing?.id}
                    open={editing !== null}
                    onOpenChange={(open) => {
                        if (!open) {
                            setEditing(null);
                        }
                    }}
                    editing={editing}
                    students={students}
                    academicTerms={academicTerms}
                    courseClasses={courseClasses}
                    lecturers={lecturers}
                />

                <DataTable
                    columns={columns}
                    data={registrations.data}
                    emptyText="Belum ada data registrasi KRS."
                    pagination={pagination}
                    onPageChange={handlePageChange}
                    onPerPageChange={handlePerPageChange}
                    onSearchChange={handleSearchChange}
                    searchValue={search}
                    searchKey="student"
                    searchPlaceholder="Cari nama atau NIM mahasiswa..."
                    toolbar={
                        <FilterDialog
                            fields={filterFields}
                            activeFilters={filters}
                            onApply={applyFilters}
                        />
                    }
                />

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

function RegistrationFields({
    errors,
    editing,
    students,
    academicTerms,
    courseClasses,
    lecturers,
}: {
    errors: Record<string, string>;
    editing?: CourseRegistration;
    students: CourseRegistrationStudent[];
    academicTerms: AcademicTermOption[];
    courseClasses: CourseRegistrationCourseClass[];
    lecturers: LecturerOption[];
}) {
    return (
        <>
            <div className="grid gap-2">
                <Label>
                    Mahasiswa <span className="text-destructive">*</span>
                </Label>
                {!editing && <input type="hidden" name="student_id" />}
                <Select
                    name="student_id"
                    defaultValue={
                        editing ? String(editing.student_id) : undefined
                    }
                >
                    <SelectTrigger className="w-full">
                        <SelectValue placeholder="Pilih mahasiswa" />
                    </SelectTrigger>
                    <SelectContent>
                        {students.map((student) => (
                            <SelectItem
                                key={student.id}
                                value={String(student.id)}
                            >
                                {studentLabel(student)}
                            </SelectItem>
                        ))}
                    </SelectContent>
                </Select>
                <InputError message={errors.student_id} />
            </div>
            <div className="grid gap-2">
                <Label>
                    Kelas Mata Kuliah{' '}
                    <span className="text-destructive">*</span>
                </Label>
                {!editing && <input type="hidden" name="course_class_id" />}
                <Select
                    name="course_class_id"
                    defaultValue={
                        editing ? String(editing.course_class_id) : undefined
                    }
                >
                    <SelectTrigger className="w-full">
                        <SelectValue placeholder="Pilih kelas mata kuliah" />
                    </SelectTrigger>
                    <SelectContent>
                        {courseClasses.map((courseClass) => (
                            <SelectItem
                                key={courseClass.id}
                                value={String(courseClass.id)}
                            >
                                {courseClassLabel(courseClass)}
                            </SelectItem>
                        ))}
                    </SelectContent>
                </Select>
                <InputError message={errors.course_class_id} />
            </div>
            <div className="grid gap-2">
                <Label>
                    Periode Akademik <span className="text-destructive">*</span>
                </Label>
                {!editing && <input type="hidden" name="academic_term_id" />}
                <Select
                    name="academic_term_id"
                    defaultValue={
                        editing ? String(editing.academic_term_id) : undefined
                    }
                >
                    <SelectTrigger className="w-full">
                        <SelectValue placeholder="Pilih periode akademik" />
                    </SelectTrigger>
                    <SelectContent>
                        {academicTerms.map((term) => (
                            <SelectItem key={term.id} value={String(term.id)}>
                                {term.name}
                            </SelectItem>
                        ))}
                    </SelectContent>
                </Select>
                <InputError message={errors.academic_term_id} />
            </div>
            <div className="grid gap-2">
                <Label>Status</Label>
                <input type="hidden" name="status" />
                <Select
                    name="status"
                    defaultValue={editing?.status ?? 'submitted'}
                >
                    <SelectTrigger className="w-full">
                        <SelectValue placeholder="Pilih status" />
                    </SelectTrigger>
                    <SelectContent>
                        {RegistrationStatuses.map((status) => (
                            <SelectItem key={status} value={status}>
                                {RegistrationStatusLabels[status]}
                            </SelectItem>
                        ))}
                    </SelectContent>
                </Select>
                <InputError message={errors.status} />
            </div>
            <div className="grid gap-2">
                <Label>Disetujui Oleh</Label>
                <input type="hidden" name="approved_by" />
                <Select
                    name="approved_by"
                    defaultValue={
                        editing?.approved_by
                            ? String(editing.approved_by)
                            : undefined
                    }
                >
                    <SelectTrigger className="w-full">
                        <SelectValue placeholder="Pilih dosen (jika disetujui)" />
                    </SelectTrigger>
                    <SelectContent>
                        {lecturers.map((lecturer) => (
                            <SelectItem
                                key={lecturer.id}
                                value={String(lecturer.id)}
                            >
                                {lecturerLabel(lecturer)}
                            </SelectItem>
                        ))}
                    </SelectContent>
                </Select>
                <InputError message={errors.approved_by} />
            </div>
        </>
    );
}

function CreateForm({
    open,
    onOpenChange,
    students,
    academicTerms,
    courseClasses,
    lecturers,
}: {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    students: CourseRegistrationStudent[];
    academicTerms: AcademicTermOption[];
    courseClasses: CourseRegistrationCourseClass[];
    lecturers: LecturerOption[];
}) {
    return (
        <FormDialog
            open={open}
            onOpenChange={onOpenChange}
            title="Tambah Registrasi KRS"
            action={store()}
            resetOnSuccess
            onSuccess={() => onOpenChange(false)}
        >
            {({ errors }) => (
                <div className="grid gap-4">
                    <RegistrationFields
                        errors={errors}
                        students={students}
                        academicTerms={academicTerms}
                        courseClasses={courseClasses}
                        lecturers={lecturers}
                    />
                </div>
            )}
        </FormDialog>
    );
}

function EditForm({
    open,
    onOpenChange,
    editing,
    students,
    academicTerms,
    courseClasses,
    lecturers,
}: {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    editing: CourseRegistration | null;
    students: CourseRegistrationStudent[];
    academicTerms: AcademicTermOption[];
    courseClasses: CourseRegistrationCourseClass[];
    lecturers: LecturerOption[];
}) {
    return (
        <FormDialog
            open={open}
            onOpenChange={onOpenChange}
            title="Edit Registrasi KRS"
            action={editing ? update(editing.id) : ''}
            resetOnSuccess
            onSuccess={() => onOpenChange(false)}
        >
            {({ errors }) =>
                editing && (
                    <div className="grid gap-4">
                        <RegistrationFields
                            errors={errors}
                            editing={editing}
                            students={students}
                            academicTerms={academicTerms}
                            courseClasses={courseClasses}
                            lecturers={lecturers}
                        />
                    </div>
                )
            }
        </FormDialog>
    );
}
