import { Form, Head, router } from '@inertiajs/react';
import { ArrowDownToLine, ArrowUpFromLine, Wallet } 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 { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import {
    Dialog,
    DialogContent,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { formatCurrency } from '@/lib/utils';
import { index as cashAccountIndex, deposit, withdrawal } from '@/routes/admin/finance/cash-accounts';
import { update as updateTransaction, destroy as destroyTransaction } from '@/routes/admin/finance/cash-accounts/transactions';
import { createTransactionColumns } from './transaction-columns';
import type { CashTransaction } from './transaction-columns';
import { DataTable } from '@/components/data-table';
import { ConfirmDialog } from '@/components/confirm-dialog';

type CashAccount = {
    id: number;
    name: string;
    balance: number;
};

type Props = {
    cashAccount: CashAccount | null;
    transactions: CashTransaction[];
};

export default function CashAccountIndex({ cashAccount, transactions }: Props) {
    const [depositOpen, setDepositOpen] = useState(false);
    const [withdrawalOpen, setWithdrawalOpen] = useState(false);
    const [editing, setEditing] = useState<CashTransaction | null>(null);
    const [deleting, setDeleting] = useState<CashTransaction | null>(null);

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

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

    const columns = createTransactionColumns({
        handleEdit: (transaction) => setEditing(transaction),
        handleDeleteClick: (transaction) => setDeleting(transaction),
    });

    return (
        <>
            <Head title="Kas Toko" />

            <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">
                            Kas Toko
                        </h2>
                    </div>
                    <div className="flex items-center gap-2">
                        <Button variant="outline" onClick={() => setDepositOpen(true)}>
                            <ArrowDownToLine className="h-4 w-4" />
                            Deposit
                        </Button>
                        <Button variant="outline" onClick={() => setWithdrawalOpen(true)}>
                            <ArrowUpFromLine className="h-4 w-4" />
                            Withdrawal
                        </Button>
                    </div>
                </div>

                <Card>
                    <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                        <CardTitle className="text-sm font-medium">
                            Saldo saat ini
                        </CardTitle>
                        <Wallet className="h-4 w-4 text-muted-foreground" />
                    </CardHeader>
                    <CardContent>
                        <div className="text-2xl font-bold">
                            {formatCurrency(cashAccount?.balance ?? 0)}
                        </div>
                    </CardContent>
                </Card>

                <DataTable
                    columns={columns}
                    data={transactions}
                    searchKey="description"
                    searchPlaceholder="Cari transaksi..."
                    emptyText="Belum ada riwayat transaksi."
                />

                <Dialog open={depositOpen} onOpenChange={setDepositOpen}>
                    <DialogContent>
                        <Form action={deposit()} resetOnSuccess onSuccess={() => setDepositOpen(false)}>
                            {({ errors, processing }) => (
                                <>
                                    <DialogHeader>
                                        <DialogTitle>Deposit</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>
                                                Keterangan <span className="text-destructive">*</span>
                                            </Label>
                                            <Input
                                                name="description"
                                                placeholder="Masukkan keterangan"
                                            />
                                            <InputError message={errors.description} />
                                        </div>
                                    </div>
                                    <DialogFooter>
                                        <Button type="button" variant="outline" onClick={() => setDepositOpen(false)}>
                                            Batal
                                        </Button>
                                        <Button type="submit" disabled={processing}>
                                            {processing ? 'Menyimpan...' : 'Simpan'}
                                        </Button>
                                    </DialogFooter>
                                </>
                            )}
                        </Form>
                    </DialogContent>
                </Dialog>

                <Dialog open={withdrawalOpen} onOpenChange={setWithdrawalOpen}>
                    <DialogContent>
                        <Form action={withdrawal()} resetOnSuccess onSuccess={() => setWithdrawalOpen(false)}>
                            {({ errors, processing }) => (
                                <>
                                    <DialogHeader>
                                        <DialogTitle>Withdrawal</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>
                                                Keterangan <span className="text-destructive">*</span>
                                            </Label>
                                            <Input
                                                name="description"
                                                placeholder="Masukkan keterangan"
                                            />
                                            <InputError message={errors.description} />
                                        </div>
                                    </div>
                                    <DialogFooter>
                                        <Button type="button" variant="outline" onClick={() => setWithdrawalOpen(false)}>
                                            Batal
                                        </Button>
                                        <Button type="submit" disabled={processing}>
                                            {processing ? 'Menyimpan...' : 'Simpan'}
                                        </Button>
                                    </DialogFooter>
                                </>
                            )}
                        </Form>
                    </DialogContent>
                </Dialog>

                <Dialog
                    open={editing !== null}
                    onOpenChange={(open) => {
                        if (!open) {
                            setEditing(null);
                        }
                    }}
                >
                    <DialogContent>
                        {editing && (
                            <Form action={updateTransaction(editing.id)} resetOnSuccess onSuccess={() => setEditing(null)}>
                                {({ errors, processing }) => (
                                    <>
                                        <DialogHeader>
                                            <DialogTitle>Edit Transaksi</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>
                                                    Keterangan <span className="text-destructive">*</span>
                                                </Label>
                                                <Input
                                                    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 Transaksi"
                    description={`Apakah Anda yakin ingin menghapus transaksi "${deleting?.description}"? Tindakan ini tidak dapat dibatalkan.`}
                    confirmLabel="Hapus"
                    onConfirm={handleDelete}
                />
            </div>
        </>
    );
}

CashAccountIndex.layout = {
    breadcrumbs: [
        {
            title: 'Keuangan',
            href: cashAccountIndex(),
        },
        {
            title: 'Kas Toko',
            href: cashAccountIndex(),
        },
    ],
};
