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 { PhoneNumberInput } from '@/components/phone-number-input';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
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 [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),
    });

    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={
                        <Button asChild>
                            <button
                                type="button"
                                onClick={() => setCreateOpen(true)}
                            >
                                <Plus className="h-4 w-4" />
                                Tambah
                            </button>
                        </Button>
                    }
                />

                <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"
                    searchPlaceholder="Cari supplier..."
                    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>
        </>
    );
}
