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 { usePermissions } from '@/hooks/use-permissions';
import { useServerTable } from '@/hooks/use-server-table';
import {
    index as departmentIndex,
    destroy,
    store,
    update,
} from '@/routes/admin/master/departments';
import { DegreeLevels } from '@/types/department';
import type { Department } from '@/types/department';
import { createDepartmentColumns } from './columns';

type Props = {
    departments: {
        data: Department[];
        current_page: number;
        last_page: number;
        per_page: number;
        total: number;
    };
    highlight?: number;
};

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

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

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

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

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

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

    return (
        <>
            <Head title="Jurusan" />

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

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

                <DataTable
                    columns={columns}
                    data={departments.data}
                    searchKey="name"
                    pagination={pagination}
                    onPageChange={handlePageChange}
                    onPerPageChange={handlePerPageChange}
                    onSearchChange={handleSearchChange}
                    searchValue={search}
                />

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

function CreateForm({
    open,
    onOpenChange,
}: {
    open: boolean;
    onOpenChange: (open: boolean) => void;
}) {
    return (
        <FormDialog
            open={open}
            onOpenChange={onOpenChange}
            title="Tambah Jurusan"
            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: SI" />
                        <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 jurusan"
                        />
                        <InputError message={errors.name} />
                    </div>
                    <div className="grid gap-2">
                        <Label>Jenjang</Label>
                        <input type="hidden" name="degree_level" />
                        <Select name="degree_level">
                            <SelectTrigger className="w-full">
                                <SelectValue placeholder="Pilih jenjang" />
                            </SelectTrigger>
                            <SelectContent>
                                {DegreeLevels.map((level) => (
                                    <SelectItem key={level} value={level}>
                                        {level}
                                    </SelectItem>
                                ))}
                            </SelectContent>
                        </Select>
                        <InputError message={errors.degree_level} />
                    </div>
                </div>
            )}
        </FormDialog>
    );
}

function EditForm({
    open,
    onOpenChange,
    editing,
}: {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    editing: Department | null;
}) {
    return (
        <FormDialog
            open={open}
            onOpenChange={onOpenChange}
            title="Edit Jurusan"
            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: SI"
                                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 jurusan"
                                defaultValue={editing.name}
                            />
                            <InputError message={errors.name} />
                        </div>
                        <div className="grid gap-2">
                            <Label>Jenjang</Label>
                            <input
                                type="hidden"
                                name="degree_level"
                                defaultValue={editing.degree_level ?? ''}
                            />
                            <Select
                                name="degree_level"
                                defaultValue={editing.degree_level ?? undefined}
                            >
                                <SelectTrigger className="w-full">
                                    <SelectValue placeholder="Pilih jenjang" />
                                </SelectTrigger>
                                <SelectContent>
                                    {DegreeLevels.map((level) => (
                                        <SelectItem key={level} value={level}>
                                            {level}
                                        </SelectItem>
                                    ))}
                                </SelectContent>
                            </Select>
                            <InputError message={errors.degree_level} />
                        </div>
                    </div>
                )
            }
        </FormDialog>
    );
}
