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 {
    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 { usePermissions } from '@/hooks/use-permissions';
import { useServerTable } from '@/hooks/use-server-table';
import {
    index as courseClassIndex,
    destroy,
    store,
    update,
} from '@/routes/admin/manage/course-classes';
import { formatAcademicTermLabel } from '@/types/academic-term';
import { ClassMethodLabels, ClassMethods } from '@/types/course-class';
import type { CourseClass } from '@/types/course-class';
import { createCourseClassColumns } from './columns';

type Course = { id: number; code: string; name: string; department_id: number };
type Lecturer = {
    id: number;
    lecturer_number: string;
    departments: { id: number; name: string }[];
    user: { profile: { full_name: string } | null } | null;
};
type AcademicTerm = { id: number; name: string; semester: string };

type Props = {
    courseClasses: {
        data: CourseClass[];
        current_page: number;
        last_page: number;
        per_page: number;
        total: number;
    };
    courses: Course[];
    lecturers: Lecturer[];
    academicTerms: AcademicTerm[];
    highlight?: number;
    filters: {
        academic_term_id?: string;
        method?: string;
    };
};

export default function CourseClassIndex({
    courseClasses,
    courses,
    lecturers,
    academicTerms,
    highlight,
    filters,
}: Props) {
    const [createOpen, setCreateOpen] = useState(false);
    const [editing, setEditing] = useState<CourseClass | null>(null);
    const [deleting, setDeleting] = useState<CourseClass | null>(null);
    const { hasPermission } = usePermissions();
    const canCreate = hasPermission('create-course-classes');
    const canUpdate = hasPermission('update-course-classes');
    const canDelete = hasPermission('delete-course-classes');
    const canViewEnrollments = hasPermission('view-course-class-enrollments');

    const filterFields: FilterField[] = [
        {
            key: 'academic_term_id',
            label: 'Periode Akademik',
            options: academicTerms.map((term) => ({
                value: String(term.id),
                label: formatAcademicTermLabel(term),
            })),
        },
        {
            key: 'method',
            label: 'Metode',
            options: ClassMethods.map((method) => ({
                value: method,
                label: ClassMethodLabels[method],
            })),
        },
    ];

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

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

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

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

    const columns = createCourseClassColumns({
        handleEdit: (courseClass) => setEditing(courseClass),
        handleDeleteClick: (courseClass) => setDeleting(courseClass),
        canUpdate,
        canDelete,
        canViewEnrollments,
    });

    return (
        <>
            <Head title="Kelas Mata Kuliah" />

            <div className="flex h-full flex-1 flex-col gap-6 overflow-x-auto p-4 md:p-6">
                <PageHeader
                    title="Kelas Mata Kuliah"
                    description={
                        highlight && (
                            <p className="mt-1 text-sm text-muted-foreground">
                                Menampilkan kelas mata kuliah dari notifikasi.
                                <button
                                    onClick={() => {
                                        router.get(
                                            courseClassIndex.url(),
                                            {},
                                            {
                                                replace: true,
                                                preserveState: true,
                                            },
                                        );
                                    }}
                                    className="ml-1 text-primary underline underline-offset-4 hover:text-primary/80"
                                >
                                    Tampilkan semua
                                </button>
                            </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}
                    courses={courses}
                    lecturers={lecturers}
                    academicTerms={academicTerms}
                />

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

                <DataTable
                    columns={columns}
                    data={courseClasses.data}
                    searchKey="course"
                    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 Kelas Mata Kuliah"
                    description={(courseClass) =>
                        `Apakah Anda yakin ingin menghapus kelas "${courseClass.course?.name}"? Tindakan ini tidak dapat dibatalkan.`
                    }
                    onConfirm={handleDelete}
                />
            </div>
        </>
    );
}

function CreateForm({
    open,
    onOpenChange,
    courses,
    lecturers,
    academicTerms,
}: {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    courses: Course[];
    lecturers: Lecturer[];
    academicTerms: AcademicTerm[];
}) {
    const [courseId, setCourseId] = useState('');
    const [lecturer, setLecturer] = useState<Lecturer | null>(null);

    const selectedCourse = courses.find((c) => String(c.id) === courseId);
    const availableLecturers = selectedCourse
        ? lecturers.filter((l) =>
              l.departments.some(
                  (department) =>
                      department.id === selectedCourse.department_id,
              ),
          )
        : lecturers;

    function reset() {
        setCourseId('');
        setLecturer(null);
    }

    return (
        <FormDialog
            open={open}
            onOpenChange={onOpenChange}
            title="Tambah Kelas Mata Kuliah"
            action={store()}
            resetOnSuccess
            onSuccess={() => {
                onOpenChange(false);
                reset();
            }}
        >
            {({ errors }) => (
                <div className="grid gap-4">
                    <div className="grid gap-2">
                        <Label>
                            Periode Akademik{' '}
                            <span className="text-destructive">*</span>
                        </Label>
                        <input type="hidden" name="academic_term_id" />
                        <Select name="academic_term_id">
                            <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>
                            Mata Kuliah{' '}
                            <span className="text-destructive">*</span>
                        </Label>
                        <input
                            type="hidden"
                            name="course_id"
                            value={courseId}
                        />
                        <Select
                            value={courseId}
                            onValueChange={(value) => {
                                setCourseId(value);
                                setLecturer(null);
                            }}
                        >
                            <SelectTrigger className="w-full">
                                <SelectValue placeholder="Pilih mata kuliah" />
                            </SelectTrigger>
                            <SelectContent>
                                {courses.map((course) => (
                                    <SelectItem
                                        key={course.id}
                                        value={String(course.id)}
                                    >
                                        {course.code} - {course.name}
                                    </SelectItem>
                                ))}
                            </SelectContent>
                        </Select>
                        <InputError message={errors.course_id} />
                    </div>
                    <div className="grid gap-2">
                        <Label>
                            Dosen Pengampu{' '}
                            <span className="text-destructive">*</span>
                        </Label>
                        <input
                            type="hidden"
                            name="lecturer_id"
                            value={lecturer?.id ?? ''}
                        />
                        <Combobox
                            items={availableLecturers}
                            value={lecturer}
                            onValueChange={setLecturer}
                            itemToStringLabel={(lect) =>
                                `${lect.user?.profile?.full_name ?? 'N/A'} - ${lect.lecturer_number}`
                            }
                            isItemEqualToValue={(a, b) => a.id === b.id}
                            disabled={!selectedCourse}
                        >
                            <ComboboxInput
                                disabled={!selectedCourse}
                                placeholder={
                                    selectedCourse
                                        ? 'Pilih dosen pengampu'
                                        : 'Pilih mata kuliah terlebih dahulu'
                                }
                                className="w-full"
                            />
                            <ComboboxContent>
                                <ComboboxEmpty>
                                    Dosen tidak ditemukan.
                                </ComboboxEmpty>
                                <ComboboxList>
                                    {(lect: Lecturer) => (
                                        <ComboboxItem
                                            key={lect.id}
                                            value={lect}
                                        >
                                            {lect.user?.profile?.full_name ??
                                                'N/A'}{' '}
                                            - {lect.lecturer_number}
                                        </ComboboxItem>
                                    )}
                                </ComboboxList>
                            </ComboboxContent>
                        </Combobox>
                        <InputError message={errors.lecturer_id} />
                    </div>
                    <div className="grid gap-2">
                        <Label>Metode</Label>
                        <input type="hidden" name="method" />
                        <Select name="method" defaultValue="hybrid">
                            <SelectTrigger className="w-full">
                                <SelectValue placeholder="Pilih metode" />
                            </SelectTrigger>
                            <SelectContent>
                                {ClassMethods.map((method) => (
                                    <SelectItem key={method} value={method}>
                                        {ClassMethodLabels[method]}
                                    </SelectItem>
                                ))}
                            </SelectContent>
                        </Select>
                        <InputError message={errors.method} />
                    </div>
                </div>
            )}
        </FormDialog>
    );
}

function EditForm({
    open,
    onOpenChange,
    editing,
    courses,
    lecturers,
    academicTerms,
}: {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    editing: CourseClass | null;
    courses: Course[];
    lecturers: Lecturer[];
    academicTerms: AcademicTerm[];
}) {
    const [courseId, setCourseId] = useState(
        editing ? String(editing.course_id) : '',
    );
    const [lecturer, setLecturer] = useState<Lecturer | null>(
        editing
            ? (lecturers.find((l) => l.id === editing.lecturer_id) ?? null)
            : null,
    );

    const selectedCourse = courses.find((c) => String(c.id) === courseId);
    const availableLecturers = selectedCourse
        ? lecturers.filter((l) =>
              l.departments.some(
                  (department) =>
                      department.id === selectedCourse.department_id,
              ),
          )
        : lecturers;

    return (
        <FormDialog
            open={open}
            onOpenChange={onOpenChange}
            title="Edit Kelas Mata Kuliah"
            action={editing ? update(editing.id) : ''}
            resetOnSuccess
            onSuccess={() => onOpenChange(false)}
        >
            {({ errors }) =>
                editing && (
                    <div className="grid gap-4">
                        <div className="grid gap-2">
                            <Label>
                                Mata Kuliah{' '}
                                <span className="text-destructive">*</span>
                            </Label>
                            <input
                                type="hidden"
                                name="course_id"
                                value={courseId}
                            />
                            <Select
                                value={courseId}
                                onValueChange={(value) => {
                                    setCourseId(value);
                                    setLecturer(null);
                                }}
                            >
                                <SelectTrigger className="w-full">
                                    <SelectValue placeholder="Pilih mata kuliah" />
                                </SelectTrigger>
                                <SelectContent>
                                    {courses.map((course) => (
                                        <SelectItem
                                            key={course.id}
                                            value={String(course.id)}
                                        >
                                            {course.code} - {course.name}
                                        </SelectItem>
                                    ))}
                                </SelectContent>
                            </Select>
                            <InputError message={errors.course_id} />
                        </div>
                        <div className="grid gap-2">
                            <Label>
                                Dosen Pengampu{' '}
                                <span className="text-destructive">*</span>
                            </Label>
                            <input
                                type="hidden"
                                name="lecturer_id"
                                value={lecturer?.id ?? ''}
                            />
                            <Combobox
                                items={availableLecturers}
                                value={lecturer}
                                onValueChange={setLecturer}
                                itemToStringLabel={(lect) =>
                                    `${lect.user?.profile?.full_name ?? 'N/A'} - ${lect.lecturer_number}`
                                }
                                isItemEqualToValue={(a, b) => a.id === b.id}
                                disabled={!selectedCourse}
                            >
                                <ComboboxInput
                                    disabled={!selectedCourse}
                                    placeholder={
                                        selectedCourse
                                            ? 'Pilih dosen pengampu'
                                            : 'Pilih mata kuliah terlebih dahulu'
                                    }
                                    className="w-full"
                                />
                                <ComboboxContent>
                                    <ComboboxEmpty>
                                        Dosen tidak ditemukan.
                                    </ComboboxEmpty>
                                    <ComboboxList>
                                        {(lect: Lecturer) => (
                                            <ComboboxItem
                                                key={lect.id}
                                                value={lect}
                                            >
                                                {lect.user?.profile
                                                    ?.full_name ?? 'N/A'}{' '}
                                                - {lect.lecturer_number}
                                            </ComboboxItem>
                                        )}
                                    </ComboboxList>
                                </ComboboxContent>
                            </Combobox>
                            <InputError message={errors.lecturer_id} />
                        </div>
                        <div className="grid gap-2">
                            <Label>
                                Periode Akademik{' '}
                                <span className="text-destructive">*</span>
                            </Label>
                            <Select
                                name="academic_term_id"
                                defaultValue={String(editing.academic_term_id)}
                            >
                                <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>Metode</Label>
                            <Select
                                name="method"
                                defaultValue={editing.method ?? 'hybrid'}
                            >
                                <SelectTrigger className="w-full">
                                    <SelectValue placeholder="Pilih metode" />
                                </SelectTrigger>
                                <SelectContent>
                                    {ClassMethods.map((method) => (
                                        <SelectItem key={method} value={method}>
                                            {ClassMethodLabels[method]}
                                        </SelectItem>
                                    ))}
                                </SelectContent>
                            </Select>
                            <InputError message={errors.method} />
                        </div>
                    </div>
                )
            }
        </FormDialog>
    );
}
