import { Form, Head, router } from '@inertiajs/react';
import { Plus } from 'lucide-react';
import { useState } from 'react';
import InputError from '@/components/input-error';
import { Button } from '@/components/ui/button';
import {
    Dialog,
    DialogContent,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { destroy, index as customerIndex, store, update } from '@/routes/admin/master/customers';
import { createCustomerColumns } from './columns';
import type { Customer } from './columns';
import { ConfirmDialog } from '@/components/confirm-dialog';
import { DataTable } from '@/components/data-table';

type Props = {
    customers: Customer[];
};

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

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

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

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

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

            <div className="flex h-full flex-1 flex-col gap-6 overflow-x-auto p-4 md:p-6">
                <div className="flex items-center justify-between">
                    <div>
                        <h2 className="text-2xl font-semibold tracking-tight">
                            Customer
                        </h2>
                    </div>
                    <Dialog open={createOpen} onOpenChange={setCreateOpen}>
                        <Button asChild>
                            <button
                                type="button"
                                onClick={() => setCreateOpen(true)}
                            >
                                <Plus className="h-4 w-4" />
                                Tambah
                            </button>
                        </Button>
                        <DialogContent>
                            <Form action={store()} resetOnSuccess onSuccess={() => setCreateOpen(false)}>
                                {({ errors, processing }) => {

                                    return (
                                        <>
                                            <DialogHeader>
                                                <DialogTitle>Tambah Customer</DialogTitle>
                                            </DialogHeader>
                                            <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>
                                                    <Input
                                                        id="phone_number"
                                                        name="phone_number"
                                                        type="tel"
                                                        inputMode="numeric"
                                                        pattern="[0-9]*"
                                                        placeholder="Masukkan nomor telepon"
                                                    />
                                                    <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>
                                            <DialogFooter>
                                                <Button
                                                    type="button"
                                                    variant="outline"
                                                    onClick={() => setCreateOpen(false)}
                                                >
                                                    Batal
                                                </Button>
                                                <Button
                                                    type='submit'
                                                    disabled={processing}
                                                >
                                                    {processing
                                                        ? 'Menyimpan...'
                                                        : 'Simpan'}
                                                </Button>
                                            </DialogFooter>
                                        </>
                                    );
                                }}
                            </Form>
                        </DialogContent>
                    </Dialog>
                </div>

                <DataTable
                    columns={columns}
                    data={customers}
                    searchKey="name"
                    searchPlaceholder="Cari customer..."
                    emptyText="Belum ada data customer."
                />

                <Dialog
                    open={editing !== null}
                    onOpenChange={(open) => {
                        if (!open) {
                            setEditing(null);
                        }
                    }}
                >
                    <DialogContent>
                        {editing && (
                            <Form action={update(editing.id)} resetOnSuccess onSuccess={() => setEditing(null)}>
                                {({ errors, processing }) => {

                                    return (
                                        <>
                                            <DialogHeader>
                                                <DialogTitle>Edit Customer</DialogTitle>
                                            </DialogHeader>
                                            <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>
                                                    <Input
                                                        id="edit-phone_number"
                                                        name="phone_number"
                                                        type="tel"
                                                        inputMode="numeric"
                                                        pattern="[0-9]*"
                                                        placeholder="Masukkan nomor telepon"
                                                        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>
                                            <DialogFooter>
                                                <Button
                                                    type="button"
                                                    variant="outline"
                                                    onClick={() => {
                                                        setEditing(null);
                                                    }}
                                                >
                                                    Batal
                                                </Button>
                                                <Button
                                                    type="submit"
                                                    disabled={processing}
                                                >
                                                    {processing
                                                        ? 'Menyimpan...'
                                                        : 'Simpan'}
                                                </Button>
                                            </DialogFooter>
                                        </>
                                    );
                                }}
                            </Form>
                        )}
                    </DialogContent>
                </Dialog>

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

CustomerIndex.layout = {
    breadcrumbs: [
        {
            title: 'Master',
            href: customerIndex(),
        },
        {
            title: 'Customer',
            href: customerIndex(),
        },
    ],
};
