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 { FormDialog } from '@/components/form-dialog';
import InputError from '@/components/input-error';
import { PageHeader } from '@/components/page-header';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
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 courseClassIndex,
    destroy,
    store,
    update,
} from '@/routes/admin/manage/course-classes';
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;
    department_id: number;
    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;
};

export default function CourseClassIndex({
    courseClasses,
    courses,
    lecturers,
    academicTerms,
    highlight,
}: Props) {
    const [createOpen, setCreateOpen] = useState(false);
    const [editing, setEditing] = useState<CourseClass | null>(null);
    const [deleting, setDeleting] = useState<CourseClass | null>(null);

    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,
    } = useServerTable({
        route: () => courseClassIndex.url(),
        pagination,
    });

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

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

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

    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={
                        <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="class_name"
                    searchPlaceholder="Cari kelas mata kuliah..."
                    emptyText="Belum ada data kelas mata kuliah."
                    pagination={pagination}
                    onPageChange={handlePageChange}
                    onPerPageChange={handlePerPageChange}
                    onSearchChange={handleSearchChange}
                    searchValue={search}
                />

                <DeleteConfirmDialog
                    target={deleting}
                    onOpenChange={(open) => {
                        if (!open) {
                            setDeleting(null);
                        }
                    }}
                    title="Hapus Kelas Mata Kuliah"
                    description={(courseClass) =>
                        `Apakah Anda yakin ingin menghapus kelas "${courseClass.class_name ?? 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 [lecturerId, setLecturerId] = useState('');

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

    function reset() {
        setCourseId('');
        setLecturerId('');
    }

    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>
                            Mata Kuliah{' '}
                            <span className="text-destructive">*</span>
                        </Label>
                        <input
                            type="hidden"
                            name="course_id"
                            value={courseId}
                        />
                        <Select
                            value={courseId}
                            onValueChange={(value) => {
                                setCourseId(value);
                                setLecturerId('');
                            }}
                        >
                            <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={lecturerId}
                        />
                        <Select
                            value={lecturerId}
                            onValueChange={setLecturerId}
                        >
                            <SelectTrigger className="w-full">
                                <SelectValue
                                    placeholder={
                                        selectedCourse
                                            ? 'Pilih dosen pengampu'
                                            : 'Pilih mata kuliah terlebih dahulu'
                                    }
                                />
                            </SelectTrigger>
                            <SelectContent>
                                {availableLecturers.map((lect) => (
                                    <SelectItem
                                        key={lect.id}
                                        value={String(lect.id)}
                                    >
                                        {lect.user?.profile?.full_name ?? 'N/A'}{' '}
                                        - {lect.lecturer_number}
                                    </SelectItem>
                                ))}
                            </SelectContent>
                        </Select>
                        <InputError message={errors.lecturer_id} />
                    </div>
                    <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)}
                                    >
                                        {term.name}
                                    </SelectItem>
                                ))}
                            </SelectContent>
                        </Select>
                        <InputError message={errors.academic_term_id} />
                    </div>
                    <div className="grid gap-2">
                        <Label htmlFor="class_name">Nama Kelas</Label>
                        <Input
                            id="class_name"
                            name="class_name"
                            placeholder="Contoh: SI-5A"
                        />
                        <InputError message={errors.class_name} />
                    </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 [lecturerId, setLecturerId] = useState(
        editing ? String(editing.lecturer_id) : '',
    );

    const selectedCourse = courses.find((c) => String(c.id) === courseId);
    const availableLecturers = selectedCourse
        ? lecturers.filter(
              (l) => l.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);
                                    setLecturerId('');
                                }}
                            >
                                <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={lecturerId}
                            />
                            <Select
                                value={lecturerId}
                                onValueChange={setLecturerId}
                            >
                                <SelectTrigger className="w-full">
                                    <SelectValue placeholder="Pilih dosen pengampu" />
                                </SelectTrigger>
                                <SelectContent>
                                    {availableLecturers.map((lect) => (
                                        <SelectItem
                                            key={lect.id}
                                            value={String(lect.id)}
                                        >
                                            {lect.user?.profile?.full_name ??
                                                'N/A'}{' '}
                                            - {lect.lecturer_number}
                                        </SelectItem>
                                    ))}
                                </SelectContent>
                            </Select>
                            <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)}
                                        >
                                            {term.name}
                                        </SelectItem>
                                    ))}
                                </SelectContent>
                            </Select>
                            <InputError message={errors.academic_term_id} />
                        </div>
                        <div className="grid gap-2">
                            <Label htmlFor="edit-class_name">Nama Kelas</Label>
                            <Input
                                id="edit-class_name"
                                name="class_name"
                                placeholder="Contoh: SI-5A"
                                defaultValue={editing.class_name ?? ''}
                            />
                            <InputError message={errors.class_name} />
                        </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>
    );
}
