import { Form, Head, router } from '@inertiajs/react';
import { Plus } from 'lucide-react';
import { useState } from 'react';
import { ConfirmDialog } from '@/components/confirm-dialog';
import { DataTable } from '@/components/data-table';
import { FileUpload } from '@/components/file-upload';
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';

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);
    const [createReceiptKey, setCreateReceiptKey] = useState<string | null>(null);
    const [editReceiptKey, setEditReceiptKey] = useState<string | null>(null);
    const [createUploading, setCreateUploading] = useState(false);
    const [editUploading, setEditUploading] = useState(false);
    const [createFileMeta, setCreateFileMeta] = useState<{ size: number; type: string } | null>(null);
    const [editFileMeta, setEditFileMeta] = useState<{ size: number; type: string } | null>(null);

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

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

    const columns = createExpenseColumns({
        handleEdit: (expense) => {
            setEditing(expense);
            setEditReceiptKey(expense.receipt_key ?? null);
        },
        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={(open) => {
                        setCreateOpen(open);

                        if (!open) {
                            setCreateReceiptKey(null);
                            setCreateFileMeta(null);
                        }
                    }}>
                        <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);
                                setCreateReceiptKey(null);
                                setCreateFileMeta(null);
                            }}>
                                {({ 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 className="grid gap-2">
                                                    <Label>Bukti{' '} <span className="text-destructive">*</span></Label>
                                                    <input type="hidden" name="receipt_key" value={createReceiptKey ?? ''} />
                                                    <input type="hidden" name="file_size" value={createFileMeta?.size ?? ''} />
                                                    <input type="hidden" name="file_mime_type" value={createFileMeta?.type ?? ''} />
                                                    <FileUpload
                                                        value={createReceiptKey}
                                                        onChange={setCreateReceiptKey}
                                                        folder="expense"
                                                        onUploadingChange={setCreateUploading}
                                                        onFileMeta={setCreateFileMeta}
                                                    />
                                                    <InputError message={errors.receipt_key} />
                                                </div>
                                            </div>
                                            <DialogFooter>
                                                <Button
                                                    type="button"
                                                    variant="outline"
                                                    onClick={() => setCreateOpen(false)}
                                                >
                                                    Batal
                                                </Button>
                                                <Button
                                                    type='submit'
                                                    disabled={processing || createUploading}
                                                >
                                                    {processing
                                                        ? 'Menyimpan...'
                                                        : createUploading
                                                            ? 'Mengunggah...'
                                                            : '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);
                            setEditReceiptKey(null);
                            setEditFileMeta(null);
                        }
                    }}
                >
                    <DialogContent>
                        {editing && (
                            <Form action={update(editing.id)} resetOnSuccess onSuccess={() => {
                                setEditing(null);
                                setEditReceiptKey(null);
                                setEditFileMeta(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 className="grid gap-2">
                                                    <Label>Bukti{' '} <span className="text-destructive">*</span></Label>
                                                    <input type="hidden" name="receipt_key" value={editReceiptKey ?? ''} />
                                                    <input type="hidden" name="file_size" value={editFileMeta?.size ?? ''} />
                                                    <input type="hidden" name="file_mime_type" value={editFileMeta?.type ?? ''} />
                                                    <FileUpload
                                                        value={editReceiptKey}
                                                        onChange={setEditReceiptKey}
                                                        folder="expense"
                                                        onUploadingChange={setEditUploading}
                                                        existingUrl={editing.receipt_url}
                                                        onFileMeta={setEditFileMeta}
                                                    />
                                                    <InputError message={errors.receipt_key} />
                                                </div>
                                            </div>
                                            <DialogFooter>
                                                <Button
                                                    type="button"
                                                    variant="outline"
                                                    onClick={() => {
                                                        setEditing(null);
                                                    }}
                                                >
                                                    Batal
                                                </Button>
                                                <Button
                                                    type="submit"
                                                    disabled={processing || editUploading}
                                                >
                                                    {processing
                                                        ? 'Menyimpan...'
                                                        : editUploading
                                                            ? 'Mengunggah...'
                                                            : '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(),
        },
    ],
};
