import { Form, Head, router } from '@inertiajs/react';
import { Plus } from 'lucide-react';
import { useState } from 'react';
import InputError from '@/components/input-error';
import { RupiahInput } from '@/components/rupiah-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, index as expenseIndex, store, update } from '@/routes/admin/finance/expenses';
import { createExpenseColumns } from './columns';
import type { Expense } from './columns';
import { ConfirmDialog } from '@/components/confirm-dialog';
import { DataTable } from '@/components/data-table';

type Props = {
    expenses: Expense[];
};

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

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

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

    const columns = createExpenseColumns({
        handleEdit: (expense) => setEditing(expense),
        handleDeleteClick: (expense) => setDeleting(expense),
    });

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

            <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">
                            Pengeluaran
                        </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 Pengeluaran</DialogTitle>
                                            </DialogHeader>
                                            <div className="grid gap-4 py-4">
                                                <div className="grid gap-2">
                                                    <Label>
                                                        Jumlah{' '} <span className="text-destructive">*</span>
                                                    </Label>
                                                    <RupiahInput name="amount" min={1} />
                                                    <InputError message={errors.amount} />
                                                </div>
                                                <div className="grid gap-2">
                                                    <Label htmlFor="description">
                                                        Keterangan{' '} <span className="text-destructive">*</span>
                                                    </Label>
                                                    <Input
                                                        id="description"
                                                        name="description"
                                                        placeholder="Masukkan keterangan"
                                                    />
                                                    <InputError message={errors.description} />
                                                </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={expenses}
                    searchKey="description"
                    searchPlaceholder="Cari pengeluaran..."
                    emptyText="Belum ada data pengeluaran."
                />

                <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 Pengeluaran</DialogTitle>
                                            </DialogHeader>
                                            <div className="grid gap-4 py-4">
                                                <div className="grid gap-2">
                                                    <Label>Jumlah{' '} <span className="text-destructive">*</span></Label>
                                                    <RupiahInput name="amount" defaultValue={editing.amount} min={1} />
                                                    <InputError message={errors.amount} />
                                                </div>
                                                <div className="grid gap-2">
                                                    <Label htmlFor="edit-description">Keterangan{' '} <span className="text-destructive">*</span></Label>
                                                    <Input
                                                        id="edit-description"
                                                        name="description"
                                                        placeholder="Masukkan keterangan"
                                                        defaultValue={editing.description}
                                                    />
                                                    <InputError message={errors.description} />
                                                </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 Pengeluaran"
                    description={`Apakah Anda yakin ingin menghapus pengeluaran "${deleting?.description}"? Tindakan ini tidak dapat dibatalkan.`}
                    confirmLabel="Hapus"
                    onConfirm={handleDelete}
                />
            </div>
        </>
    );
}

ExpenseIndex.layout = {
    breadcrumbs: [
        {
            title: 'Keuangan',
            href: expenseIndex(),
        },
        {
            title: 'Pengeluaran',
            href: expenseIndex(),
        },
    ],
};
