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 customerIndex,
    store,
    update,
} from '@/routes/admin/master/customers';
import type { Customer } from './columns';
import { createCustomerColumns } from './columns';

type Props = {
    customers: {
        data: Customer[];
        current_page: number;
        last_page: number;
        per_page: number;
        total: number;
    };
};

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

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

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

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

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

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

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

            <div className="flex h-full flex-1 flex-col gap-6 overflow-x-auto p-4 md:p-6">
                <PageHeader
                    title="Customer"
                    actions={
                        can('customers.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 Customer"
                    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 customer"
                                />
                                <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 Customer"
                    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 customer"
                                        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={customers.data}
                    searchKey="name"

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

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