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 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 { Checkbox } from '@/components/ui/checkbox';
import {
    Combobox,
    ComboboxContent,
    ComboboxEmpty,
    ComboboxInput,
    ComboboxItem,
    ComboboxList,
} from '@/components/ui/combobox';
import { Label } from '@/components/ui/label';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
import { usePermissions } from '@/hooks/use-permissions';
import { useServerTable } from '@/hooks/use-server-table';
import {
    index as courseRegistrationIndex,
    approve,
    reject,
    store,
} from '@/routes/admin/manage/course-registrations';
import { formatAcademicTermLabel } from '@/types/academic-term';
import type {
    CourseRegistrationCourseClass,
    CourseRegistrationStudent,
    CourseRegistrationSubmission,
} from '@/types/course-registration';
import {
    RegistrationStatuses,
    RegistrationStatusLabels,
} from '@/types/course-registration';
import { createCourseRegistrationColumns } from './columns';

type AcademicTermOption = {
    id: number;
    name: string;
    semester: string;
    is_active: boolean;
};

type Props = {
    registrations: {
        data: CourseRegistrationSubmission[];
        current_page: number;
        last_page: number;
        per_page: number;
        total: number;
    };
    students: CourseRegistrationStudent[];
    academicTerms: AcademicTermOption[];
    courseClasses: CourseRegistrationCourseClass[];
    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'}`;
}

export default function CourseRegistrationIndex({
    registrations,
    students,
    academicTerms,
    courseClasses,
    highlight,
    filters,
}: Props) {
    const [createOpen, setCreateOpen] = useState(false);
    const [rejecting, setRejecting] =
        useState<CourseRegistrationSubmission | null>(null);
    const { hasPermission } = usePermissions();
    const canCreate = hasPermission('create-course-registrations');
    const canApprove = hasPermission('approve-course-registrations');
    const canReject = hasPermission('reject-course-registrations');

    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: formatAcademicTermLabel(term),
            })),
        },
    ];

    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 handleApprove(submission: CourseRegistrationSubmission) {
        router.patch(approve(submission.id));
    }

    const columns = createCourseRegistrationColumns({
        handleApprove,
        handleRejectClick: (submission) => setRejecting(submission),
        canApprove,
        canReject,
    });

    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={
                        canCreate && (
                            <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}
                />

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

                <RejectForm
                    open={rejecting !== null}
                    onOpenChange={(open) => {
                        if (!open) {
                            setRejecting(null);
                        }
                    }}
                    submission={rejecting}
                />
            </div>
        </>
    );
}

function RejectForm({
    open,
    onOpenChange,
    submission,
}: {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    submission: CourseRegistrationSubmission | null;
}) {
    return (
        <FormDialog
            open={open}
            onOpenChange={onOpenChange}
            title="Tolak Registrasi KRS"
            action={submission ? reject(submission.id) : ''}
            resetOnSuccess
            onSuccess={() => onOpenChange(false)}
        >
            {({ errors }) => (
                <div className="grid gap-4">
                    <p className="text-sm text-muted-foreground">
                        KRS milik{' '}
                        <span className="font-medium text-foreground">
                            {submission?.student?.user?.profile?.full_name ??
                                'mahasiswa ini'}
                        </span>{' '}
                        akan ditolak. Mahasiswa perlu memperbaiki dan mengajukan
                        ulang.
                    </p>
                    <div className="grid gap-2">
                        <Label htmlFor="reason">
                            Alasan Penolakan{' '}
                            <span className="text-destructive">*</span>
                        </Label>
                        <Textarea
                            id="reason"
                            name="reason"
                            placeholder="Jelaskan alasan penolakan"
                        />
                        <InputError message={errors.reason} />
                    </div>
                </div>
            )}
        </FormDialog>
    );
}

function RegistrationFields({
    errors,
    students,
    academicTerms,
    courseClasses,
}: {
    errors: Record<string, string>;
    students: CourseRegistrationStudent[];
    academicTerms: AcademicTermOption[];
    courseClasses: CourseRegistrationCourseClass[];
}) {
    const activeTermId = academicTerms.find((term) => term.is_active)?.id;

    const [student, setStudent] = useState<CourseRegistrationStudent | null>(
        null,
    );
    const [academicTermId, setAcademicTermId] = useState(() =>
        activeTermId ? String(activeTermId) : '',
    );

    const availableCourseClasses = courseClasses.filter(
        (courseClass) =>
            student &&
            academicTermId &&
            courseClass.academic_term_id === Number(academicTermId) &&
            courseClass.course?.semester_number === student.current_semester &&
            courseClass.course?.department_id === student.department?.id,
    );

    const selectionKey = `${student?.id ?? ''}-${academicTermId}`;
    const [selected, setSelected] = useState<number[]>([]);
    const [selectedForKey, setSelectedForKey] = useState(selectionKey);

    if (selectionKey !== selectedForKey) {
        setSelectedForKey(selectionKey);
        setSelected([]);
    }

    function toggle(courseClassId: number, checked: boolean) {
        setSelected((prev) =>
            checked
                ? [...prev, courseClassId]
                : prev.filter((id) => id !== courseClassId),
        );
    }

    return (
        <>
            <div className="grid gap-2">
                <Label>
                    Mahasiswa <span className="text-destructive">*</span>
                </Label>
                <input
                    type="hidden"
                    name="student_id"
                    value={student?.id ?? ''}
                />
                <Combobox
                    items={students}
                    value={student}
                    onValueChange={setStudent}
                    itemToStringLabel={studentLabel}
                    isItemEqualToValue={(a, b) => a.id === b.id}
                >
                    <ComboboxInput
                        placeholder="Pilih mahasiswa"
                        className="w-full"
                    />
                    <ComboboxContent>
                        <ComboboxEmpty>
                            Mahasiswa tidak ditemukan.
                        </ComboboxEmpty>
                        <ComboboxList>
                            {(option: CourseRegistrationStudent) => (
                                <ComboboxItem key={option.id} value={option}>
                                    {studentLabel(option)}
                                </ComboboxItem>
                            )}
                        </ComboboxList>
                    </ComboboxContent>
                </Combobox>
                <InputError message={errors.student_id} />
            </div>
            <div className="grid gap-2">
                <Label>
                    Periode Akademik <span className="text-destructive">*</span>
                </Label>
                <input
                    type="hidden"
                    name="academic_term_id"
                    value={academicTermId}
                />
                <Select
                    value={academicTermId}
                    onValueChange={setAcademicTermId}
                >
                    <SelectTrigger className="w-full">
                        <SelectValue placeholder="Pilih periode akademik" />
                    </SelectTrigger>
                    <SelectContent>
                        {academicTerms.map((term) => (
                            <SelectItem key={term.id} value={String(term.id)}>
                                {formatAcademicTermLabel(term)}
                            </SelectItem>
                        ))}
                    </SelectContent>
                </Select>
                <InputError message={errors.academic_term_id} />
            </div>
            <div className="grid gap-2">
                <Label>
                    Kelas Mata Kuliah{' '}
                    <span className="text-destructive">*</span>
                </Label>
                {!student || !academicTermId ? (
                    <p className="text-sm text-muted-foreground">
                        Pilih mahasiswa dan periode terlebih dahulu.
                    </p>
                ) : availableCourseClasses.length === 0 ? (
                    <p className="text-sm text-muted-foreground">
                        Tidak ada kelas mata kuliah yang tersedia untuk semester
                        mahasiswa ini.
                    </p>
                ) : (
                    <div className="grid max-h-64 gap-1 overflow-y-auto rounded-md border p-2">
                        {availableCourseClasses.map((courseClass) => (
                            <label
                                key={courseClass.id}
                                className="flex items-center gap-2 rounded-md p-2 hover:bg-muted"
                            >
                                <Checkbox
                                    checked={selected.includes(courseClass.id)}
                                    onCheckedChange={(checked) =>
                                        toggle(courseClass.id, checked === true)
                                    }
                                />
                                <span className="text-sm">
                                    {courseClassLabel(courseClass)}
                                </span>
                            </label>
                        ))}
                    </div>
                )}
                {selected.map((courseClassId) => (
                    <input
                        key={courseClassId}
                        type="hidden"
                        name="course_class_ids[]"
                        value={courseClassId}
                    />
                ))}
                <InputError message={errors.course_class_ids} />
            </div>
        </>
    );
}

function CreateForm({
    open,
    onOpenChange,
    students,
    academicTerms,
    courseClasses,
}: {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    students: CourseRegistrationStudent[];
    academicTerms: AcademicTermOption[];
    courseClasses: CourseRegistrationCourseClass[];
}) {
    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}
                    />
                </div>
            )}
        </FormDialog>
    );
}
