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 { Input } from '@/components/ui/input';
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 courseIndex,
    destroy,
    store,
    update,
} from '@/routes/admin/master/courses';
import type { Course } from '@/types/course';
import { formatDepartmentLabel } from '@/types/department';
import { createCourseColumns } from './columns';

type Department = { id: number; name: string; degree_level: string | null };

type Props = {
    courses: {
        data: Course[];
        current_page: number;
        last_page: number;
        per_page: number;
        total: number;
    };
    departments: Department[];
    semesterNumbers: number[];
    highlight?: number;
    filters: {
        department_id?: string;
        semester_number?: string;
    };
};

export default function CourseIndex({
    courses,
    departments,
    semesterNumbers,
    highlight,
    filters,
}: Props) {
    const [createOpen, setCreateOpen] = useState(false);
    const [editing, setEditing] = useState<Course | null>(null);
    const [deleting, setDeleting] = useState<Course | null>(null);
    const { hasPermission } = usePermissions();
    const canCreate = hasPermission('create-courses');
    const canUpdate = hasPermission('update-courses');
    const canDelete = hasPermission('delete-courses');

    const filterFields: FilterField[] = [
        {
            key: 'department_id',
            label: 'Jurusan',
            options: departments.map((department) => ({
                value: String(department.id),
                label: formatDepartmentLabel(department),
            })),
        },
        {
            key: 'semester_number',
            label: 'Semester',
            options: semesterNumbers.map((semester) => ({
                value: String(semester),
                label: String(semester),
            })),
        },
    ];

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

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

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

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

    const columns = createCourseColumns({
        handleEdit: (course) => setEditing(course),
        handleDeleteClick: (course) => setDeleting(course),
        canUpdate,
        canDelete,
    });

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

            <div className="flex h-full flex-1 flex-col gap-6 overflow-x-auto p-4 md:p-6">
                <PageHeader
                    title="Mata Kuliah"
                    description={
                        highlight && (
                            <p className="mt-1 text-sm text-muted-foreground">
                                Menampilkan mata kuliah dari notifikasi.
                                <button
                                    onClick={() => {
                                        router.get(
                                            courseIndex.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}
                    departments={departments}
                />

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

                <DataTable
                    columns={columns}
                    data={courses.data}
                    searchKey="name"
                    pagination={pagination}
                    onPageChange={handlePageChange}
                    onPerPageChange={handlePerPageChange}
                    onSearchChange={handleSearchChange}
                    searchValue={search}
                    groupBy={(course) =>
                        `${course.department?.name ?? 'Tanpa Jurusan'} - Semester ${course.semester_number ?? 'Tidak ditentukan'}`
                    }
                    toolbar={
                        <FilterDialog
                            fields={filterFields}
                            activeFilters={filters}
                            onApply={applyFilters}
                        />
                    }
                />

                <DeleteConfirmDialog
                    target={deleting}
                    onOpenChange={(open) => {
                        if (!open) {
                            setDeleting(null);
                        }
                    }}
                    title="Hapus Mata Kuliah"
                    description={(course) =>
                        `Apakah Anda yakin ingin menghapus mata kuliah "${course.name}"? Tindakan ini tidak dapat dibatalkan.`
                    }
                    onConfirm={handleDelete}
                />
            </div>
        </>
    );
}

function CreateForm({
    open,
    onOpenChange,
    departments,
}: {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    departments: Department[];
}) {
    return (
        <FormDialog
            open={open}
            onOpenChange={onOpenChange}
            title="Tambah Mata Kuliah"
            action={store()}
            resetOnSuccess
            onSuccess={() => onOpenChange(false)}
        >
            {({ errors }) => (
                <div className="grid gap-4">
                    <div className="grid gap-2">
                        <Label htmlFor="code">
                            Kode <span className="text-destructive">*</span>
                        </Label>
                        <Input
                            id="code"
                            name="code"
                            placeholder="Contoh: SI301"
                        />
                        <InputError message={errors.code} />
                    </div>
                    <div className="grid gap-2">
                        <Label htmlFor="name">
                            Nama <span className="text-destructive">*</span>
                        </Label>
                        <Input
                            id="name"
                            name="name"
                            placeholder="Masukkan nama mata kuliah"
                        />
                        <InputError message={errors.name} />
                    </div>
                    <div className="grid gap-2">
                        <Label>
                            Jurusan <span className="text-destructive">*</span>
                        </Label>
                        <input type="hidden" name="department_id" />
                        <Select name="department_id">
                            <SelectTrigger className="w-full">
                                <SelectValue placeholder="Pilih jurusan" />
                            </SelectTrigger>
                            <SelectContent>
                                {departments.map((dept) => (
                                    <SelectItem
                                        key={dept.id}
                                        value={String(dept.id)}
                                    >
                                        {formatDepartmentLabel(dept)}
                                    </SelectItem>
                                ))}
                            </SelectContent>
                        </Select>
                        <InputError message={errors.department_id} />
                    </div>
                    <div className="grid grid-cols-2 gap-4">
                        <div className="grid gap-2">
                            <Label htmlFor="credits">
                                SKS <span className="text-destructive">*</span>
                            </Label>
                            <Input
                                id="credits"
                                name="credits"
                                type="number"
                                min={1}
                                max={10}
                                placeholder="Contoh: 3"
                            />
                            <InputError message={errors.credits} />
                        </div>
                        <div className="grid gap-2">
                            <Label htmlFor="semester_number">Semester</Label>
                            <Input
                                id="semester_number"
                                name="semester_number"
                                type="number"
                                min={1}
                                max={14}
                                placeholder="Contoh: 5"
                            />
                            <InputError message={errors.semester_number} />
                        </div>
                    </div>
                </div>
            )}
        </FormDialog>
    );
}

function EditForm({
    open,
    onOpenChange,
    editing,
    departments,
}: {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    editing: Course | null;
    departments: Department[];
}) {
    return (
        <FormDialog
            open={open}
            onOpenChange={onOpenChange}
            title="Edit Mata Kuliah"
            action={editing ? update(editing.id) : ''}
            resetOnSuccess
            onSuccess={() => onOpenChange(false)}
        >
            {({ errors }) =>
                editing && (
                    <div className="grid gap-4">
                        <div className="grid gap-2">
                            <Label htmlFor="edit-code">
                                Kode <span className="text-destructive">*</span>
                            </Label>
                            <Input
                                id="edit-code"
                                name="code"
                                placeholder="Contoh: SI301"
                                defaultValue={editing.code}
                            />
                            <InputError message={errors.code} />
                        </div>
                        <div className="grid gap-2">
                            <Label htmlFor="edit-name">
                                Nama <span className="text-destructive">*</span>
                            </Label>
                            <Input
                                id="edit-name"
                                name="name"
                                placeholder="Masukkan nama mata kuliah"
                                defaultValue={editing.name}
                            />
                            <InputError message={errors.name} />
                        </div>
                        <div className="grid gap-2">
                            <Label>
                                Jurusan{' '}
                                <span className="text-destructive">*</span>
                            </Label>
                            <Select
                                name="department_id"
                                defaultValue={String(editing.department_id)}
                            >
                                <SelectTrigger className="w-full">
                                    <SelectValue placeholder="Pilih jurusan" />
                                </SelectTrigger>
                                <SelectContent>
                                    {departments.map((dept) => (
                                        <SelectItem
                                            key={dept.id}
                                            value={String(dept.id)}
                                        >
                                            {formatDepartmentLabel(dept)}
                                        </SelectItem>
                                    ))}
                                </SelectContent>
                            </Select>
                            <InputError message={errors.department_id} />
                        </div>
                        <div className="grid grid-cols-2 gap-4">
                            <div className="grid gap-2">
                                <Label htmlFor="edit-credits">
                                    SKS{' '}
                                    <span className="text-destructive">*</span>
                                </Label>
                                <Input
                                    id="edit-credits"
                                    name="credits"
                                    type="number"
                                    min={1}
                                    max={10}
                                    defaultValue={editing.credits}
                                />
                                <InputError message={errors.credits} />
                            </div>
                            <div className="grid gap-2">
                                <Label htmlFor="edit-semester_number">
                                    Semester
                                </Label>
                                <Input
                                    id="edit-semester_number"
                                    name="semester_number"
                                    type="number"
                                    min={1}
                                    max={14}
                                    defaultValue={
                                        editing.semester_number ?? undefined
                                    }
                                />
                                <InputError message={errors.semester_number} />
                            </div>
                        </div>
                    </div>
                )
            }
        </FormDialog>
    );
}
