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 { PhoneNumberInput } from '@/components/inputs';
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 {
    destroy,
    index as supplierIndex,
    store,
    update,
} from '@/routes/admin/master/suppliers';
import type { Supplier } from './columns';
import { createSupplierColumns } from './columns';

type Props = {
    suppliers: {
        data: Supplier[];
        current_page: number;
        last_page: number;
        per_page: number;
        total: number;
    };
};

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

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

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

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

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

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

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

            <div className="flex h-full flex-1 flex-col gap-6 overflow-x-auto p-4 md:p-6">
                <PageHeader
                    title="Supplier"
                    actions={
                        can('suppliers.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 Supplier"
                    action={store()}
                    resetOnSuccess
                    onSuccess={() => setCreateOpen(false)}
                >
                    {({ errors }) => (
                        <div className="grid gap-4 py-4">
                            <div className="grid gap-2">
                                <Label htmlFor="name">
                                    Nama{' '}
                                    <span className="text-destructive">*</span>
                                </Label>
                                <Input
                                    id="name"
                                    name="name"
                                    placeholder="Masukkan nama supplier"
                                />
                                <InputError message={errors.name} />
                            </div>
                            <div className="grid gap-2">
                                <Label htmlFor="phone_number">
                                    No. Telepon
                                </Label>
                                <PhoneNumberInput name="phone_number" />
                                <InputError message={errors.phone_number} />
                            </div>
                            <div className="grid gap-2">
                                <Label htmlFor="address">Alamat</Label>
                                <Input
                                    id="address"
                                    name="address"
                                    placeholder="Masukkan alamat"
                                />
                                <InputError message={errors.address} />
                            </div>
                        </div>
                    )}
                </FormDialog>

                <FormDialog
                    open={editing !== null}
                    onOpenChange={(open) => {
                        if (!open) {
                            setEditing(null);
                        }
                    }}
                    title="Edit Supplier"
                    action={editing ? update(editing.id) : ''}
                    resetOnSuccess
                    onSuccess={() => setEditing(null)}
                >
                    {({ errors }) =>
                        editing && (
                            <div className="grid gap-4 py-4">
                                <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 supplier"
                                        defaultValue={editing.name}
                                    />
                                    <InputError message={errors.name} />
                                </div>
                                <div className="grid gap-2">
                                    <Label htmlFor="edit-phone_number">
                                        No. Telepon
                                    </Label>
                                    <PhoneNumberInput
                                        name="phone_number"
                                        defaultValue={editing.phone_number}
                                    />
                                    <InputError message={errors.phone_number} />
                                </div>
                                <div className="grid gap-2">
                                    <Label htmlFor="edit-address">Alamat</Label>
                                    <Input
                                        id="edit-address"
                                        name="address"
                                        placeholder="Masukkan alamat"
                                        defaultValue={editing.address ?? ''}
                                    />
                                    <InputError message={errors.address} />
                                </div>
                            </div>
                        )
                    }
                </FormDialog>

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

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

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