import { Head, router } from '@inertiajs/react';
import { Plus } from 'lucide-react';
import { useState } from 'react';
import type { PaginationState } from '@/components/data-display';
import { DataTable } from '@/components/data-display';
import { DeleteConfirmDialog } from '@/components/dialogs';
import { FormDialog } from '@/components/dialogs';
import { InputError } from '@/components/ui';
import { PageHeader } from '@/components/layout';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useCan } from '@/hooks/use-can';
import { useServerTable } from '@/hooks/use-server-table';
import {
    index as categoryIndex,
    destroy,
    store,
    update,
} from '@/routes/admin/master/categories';
import type { Category } from './columns';
import { createCategoryColumns } from './columns';

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

export default function CategoryIndex({ categories, highlight }: Props) {
    const { can } = useCan();
    const [createOpen, setCreateOpen] = useState(false);
    const [editing, setEditing] = useState<Category | null>(null);
    const [deleting, setDeleting] = useState<Category | null>(null);

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

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

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

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

    const columns = createCategoryColumns({
        handleEdit: (category) => setEditing(category),
        handleDeleteClick: (category) => setDeleting(category),
        can,
    });

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

            <div className="flex h-full flex-1 flex-col gap-6 overflow-x-auto p-4 md:p-6">
                <PageHeader
                    title="Kategori"
                    description={
                        highlight && (
                            <p className="mt-1 text-sm text-muted-foreground">
                                Menampilkan kategori dari notifikasi.
                                <button
                                    onClick={() => {
                                        router.get(
                                            categoryIndex.url(),
                                            {},
                                            {
                                                replace: true,
                                                preserveState: true,
                                            },
                                        );
                                    }}
                                    className="ml-1 text-primary underline underline-offset-4 hover:text-primary/80"
                                >
                                    Tampilkan semua
                                </button>
                            </p>
                        )
                    }
                    actions={
                        can('categories.create') ? (
                            <Button asChild>
                                <button
                                    type="button"
                                    onClick={() => setCreateOpen(true)}
                                >
                                    <Plus className="h-4 w-4" />
                                    Tambah
                                </button>
                            </Button>
                        ) : undefined
                    }
                />

                <FormDialog
                    open={createOpen}
                    onOpenChange={setCreateOpen}
                    title="Tambah Kategori"
                    action={store()}
                    resetOnSuccess
                    onSuccess={() => setCreateOpen(false)}
                >
                    {({ errors }) => (
                        <div className="grid gap-2">
                            <Label htmlFor="name">
                                Nama <span className="text-destructive">*</span>
                            </Label>
                            <Input
                                id="name"
                                name="name"
                                placeholder="Masukkan nama kategori"
                            />
                            <InputError message={errors.name} />
                        </div>
                    )}
                </FormDialog>

                <FormDialog
                    open={editing !== null}
                    onOpenChange={(open) => {
                        if (!open) {
                            setEditing(null);
                        }
                    }}
                    title="Edit Kategori"
                    action={editing ? update(editing.id) : ''}
                    resetOnSuccess
                    onSuccess={() => setEditing(null)}
                >
                    {({ errors }) =>
                        editing && (
                            <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 kategori"
                                    defaultValue={editing.name}
                                />
                                <InputError message={errors.name} />
                            </div>
                        )
                    }
                </FormDialog>

                <DataTable
                    columns={columns}
                    data={categories.data}
                    searchKey="name"

                    emptyText="Belum ada data kategori."
                    pagination={pagination}
                    onPageChange={handlePageChange}
                    onPerPageChange={handlePerPageChange}
                    onSearchChange={handleSearchChange}
                    searchValue={search}
                />

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