import { Form, Head, router } from '@inertiajs/react';
import { Plus } from 'lucide-react';
import { useCallback, useState } from 'react';
import { ConfirmDialog } from '@/components/confirm-dialog';
import { DataTable } from '@/components/data-table';
import type { PaginationState, SortState } from '@/components/data-table';
import InputError from '@/components/input-error';
import { PhoneNumberInput } from '@/components/phone-number-input';
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, store, index as supplierIndex, 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 [search, setSearch] = useState('');
    const [sort, setSort] = useState<SortState>({ column: 'created_at', direction: 'desc' });

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

    function handlePageChange(page: number) {
        router.get(supplierIndex.url(), {
            page,
            per_page: pagination.per_page,
            search,
            sort: sort.column,
            direction: sort.direction,
        }, {
            preserveState: true,
            replace: true,
        });
    }

    function handlePerPageChange(perPage: number) {
        router.get(supplierIndex.url(), {
            page: 1,
            per_page: perPage,
            search,
            sort: sort.column,
            direction: sort.direction,
        }, {
            preserveState: true,
            replace: true,
        });
    }

    const handleSearchChange = useCallback((value: string) => {
        setSearch(value);
        router.get(supplierIndex.url(), {
            page: 1,
            per_page: pagination.per_page,
            search: value,
            sort: sort.column,
            direction: sort.direction,
        }, {
            preserveState: true,
            replace: true,
        });
    }, [pagination.per_page, sort]);

    function handleSortChange(column: string, direction: 'asc' | 'desc') {
        setSort({ column, direction });
        router.get(supplierIndex.url(), {
            page: 1,
            per_page: pagination.per_page,
            search,
            sort: column,
            direction,
        }, {
            preserveState: true,
            replace: true,
        });
    }

    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">
                <div className="flex items-center justify-between">
                    <div>
                        <h2 className="text-2xl font-semibold tracking-tight">
                            Supplier
                        </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 Supplier</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 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>
                                            <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={suppliers.data}
                    searchKey="name"
                    searchPlaceholder="Cari supplier..."
                    emptyText="Belum ada data supplier."
                    pagination={pagination}
                    onPageChange={handlePageChange}
                    onPerPageChange={handlePerPageChange}
                    onSearchChange={handleSearchChange}
                    onSortChange={handleSortChange}
                    currentSort={sort}
                    searchValue={search}
                />

                <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 Supplier</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 supplier"
                                                        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 Supplier"
                    description={`Apakah Anda yakin ingin menghapus supplier "${deleting?.name}"? Tindakan ini tidak dapat dibatalkan.`}
                    confirmLabel="Hapus"
                    onConfirm={handleDelete}
                />
            </div>
        </>
    );
}

SupplierIndex.layout = {
    breadcrumbs: [
        {
            title: 'Master',
            href: supplierIndex(),
        },
        {
            title: 'Supplier',
            href: supplierIndex(),
        },
    ],
};
