import { Form, Head, router } from '@inertiajs/react';
import { ArrowDownToLine, ArrowUpFromLine, Filter, Wallet, X } 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 { 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 { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
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';

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

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

export default function CashAccountIndex({ cashAccount, transactions, filters }: 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);
    const [filterOpen, setFilterOpen] = useState(false);

    const [depositReceiptKey, setDepositReceiptKey] = useState<string | null>(null);
    const [depositUploading, setDepositUploading] = useState(false);
    const [depositFileMeta, setDepositFileMeta] = useState<{ size: number; type: string } | null>(null);

    const [withdrawalReceiptKey, setWithdrawalReceiptKey] = useState<string | null>(null);
    const [withdrawalUploading, setWithdrawalUploading] = useState(false);
    const [withdrawalFileMeta, setWithdrawalFileMeta] = useState<{ size: number; type: string } | null>(null);

    const [editReceiptKey, setEditReceiptKey] = useState<string | null>(null);
    const [editUploading, setEditUploading] = useState(false);
    const [editFileMeta, setEditFileMeta] = useState<{ size: number; type: string } | null>(null);

    const hasActiveFilters = filters.type;

    function applyFilter(key: string, value: string) {
        const newFilters = { ...filters };

        if (value === '' || value === 'all') {
            delete newFilters[key as keyof typeof newFilters];
        } else {
            newFilters[key as keyof typeof newFilters] = value;
        }

        router.get(cashAccountIndex(), newFilters, {
            preserveState: true,
            replace: true,
        });
    }

    function clearFilters() {
        router.get(cashAccountIndex(), {}, {
            preserveState: true,
            replace: true,
        });
        setFilterOpen(false);
    }

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

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

    const columns = createTransactionColumns({
        handleEdit: (transaction) => {
            setEditing(transaction);
            setEditReceiptKey(transaction.receipt_key ?? null);
        },
        handleDeleteClick: (transaction) => setDeleting(transaction),
    });

    const filterToolbar = (
        <Popover open={filterOpen} onOpenChange={setFilterOpen}>
            <PopoverTrigger asChild>
                <Button variant="outline" size="sm">
                    <Filter className="h-4 w-4" />
                    Filter
                    {hasActiveFilters && (
                        <span className="ml-1 flex h-5 w-5 items-center justify-center rounded-full bg-primary text-xs text-primary-foreground">
                            {Object.values(filters).filter(Boolean).length}
                        </span>
                    )}
                </Button>
            </PopoverTrigger>
            <PopoverContent className="w-64" align="end">
                <div className="flex flex-col gap-4">
                    <div className="flex items-center justify-between">
                        <span className="text-sm font-medium">Filter</span>
                        {hasActiveFilters && (
                            <Button
                                variant="ghost"
                                size="sm"
                                className="h-6 px-2 text-xs"
                                onClick={clearFilters}
                            >
                                <X className="mr-1 h-3 w-3" />
                                Hapus Semua
                            </Button>
                        )}
                    </div>

                    <div className="flex flex-col gap-2">
                        <label className="text-xs text-muted-foreground">
                            Tipe Sumber
                        </label>
                        <Select
                            value={filters.type ?? 'all'}
                            onValueChange={(value) => applyFilter('type', value)}
                        >
                            <SelectTrigger className="w-full">
                                <SelectValue placeholder="Semua Tipe" />
                            </SelectTrigger>
                            <SelectContent>
                                <SelectItem value="all">Semua Tipe</SelectItem>
                                <SelectItem value="deposit">Deposit</SelectItem>
                                <SelectItem value="withdrawal">Withdrawal</SelectItem>
                                <SelectItem value="expense">Pengeluaran</SelectItem>
                                <SelectItem value="transfer">Transfer</SelectItem>
                            </SelectContent>
                        </Select>
                    </div>
                </div>
            </PopoverContent>
        </Popover>
    );

    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."
                    toolbar={filterToolbar}
                />

                <Dialog open={depositOpen} onOpenChange={(open) => {
                    setDepositOpen(open);
                    if (!open) {
                        setDepositReceiptKey(null);
                        setDepositFileMeta(null);
                    }
                }}>
                    <DialogContent>
                        <Form action={deposit()} resetOnSuccess onSuccess={() => {
                            setDepositOpen(false);
                            setDepositReceiptKey(null);
                            setDepositFileMeta(null);
                        }}>
                            {({ 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 className="grid gap-2">
                                            <Label>Bukti{' '} <span className="text-destructive">*</span></Label>
                                            <input type="hidden" name="receipt_key" value={depositReceiptKey ?? ''} />
                                            <input type="hidden" name="file_size" value={depositFileMeta?.size ?? ''} />
                                            <input type="hidden" name="file_mime_type" value={depositFileMeta?.type ?? ''} />
                                            <FileUpload
                                                value={depositReceiptKey}
                                                onChange={setDepositReceiptKey}
                                                folder="cash-transaction"
                                                onUploadingChange={setDepositUploading}
                                                onFileMeta={setDepositFileMeta}
                                            />
                                            <InputError message={errors.receipt_key} />
                                        </div>
                                    </div>
                                    <DialogFooter>
                                        <Button type="button" variant="outline" onClick={() => setDepositOpen(false)}>
                                            Batal
                                        </Button>
                                        <Button type="submit" disabled={processing || depositUploading}>
                                            {processing
                                                ? 'Menyimpan...'
                                                : depositUploading
                                                    ? 'Mengunggah...'
                                                    : 'Simpan'}
                                        </Button>
                                    </DialogFooter>
                                </>
                            )}
                        </Form>
                    </DialogContent>
                </Dialog>

                <Dialog open={withdrawalOpen} onOpenChange={(open) => {
                    setWithdrawalOpen(open);
                    if (!open) {
                        setWithdrawalReceiptKey(null);
                        setWithdrawalFileMeta(null);
                    }
                }}>
                    <DialogContent>
                        <Form action={withdrawal()} resetOnSuccess onSuccess={() => {
                            setWithdrawalOpen(false);
                            setWithdrawalReceiptKey(null);
                            setWithdrawalFileMeta(null);
                        }}>
                            {({ 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 className="grid gap-2">
                                            <Label>Bukti{' '} <span className="text-destructive">*</span></Label>
                                            <input type="hidden" name="receipt_key" value={withdrawalReceiptKey ?? ''} />
                                            <input type="hidden" name="file_size" value={withdrawalFileMeta?.size ?? ''} />
                                            <input type="hidden" name="file_mime_type" value={withdrawalFileMeta?.type ?? ''} />
                                            <FileUpload
                                                value={withdrawalReceiptKey}
                                                onChange={setWithdrawalReceiptKey}
                                                folder="cash-transaction"
                                                onUploadingChange={setWithdrawalUploading}
                                                onFileMeta={setWithdrawalFileMeta}
                                            />
                                            <InputError message={errors.receipt_key} />
                                        </div>
                                    </div>
                                    <DialogFooter>
                                        <Button type="button" variant="outline" onClick={() => setWithdrawalOpen(false)}>
                                            Batal
                                        </Button>
                                        <Button type="submit" disabled={processing || withdrawalUploading}>
                                            {processing
                                                ? 'Menyimpan...'
                                                : withdrawalUploading
                                                    ? 'Mengunggah...'
                                                    : 'Simpan'}
                                        </Button>
                                    </DialogFooter>
                                </>
                            )}
                        </Form>
                    </DialogContent>
                </Dialog>

                <Dialog
                    open={editing !== null}
                    onOpenChange={(open) => {
                        if (!open) {
                            setEditing(null);
                            setEditReceiptKey(null);
                            setEditFileMeta(null);
                        }
                    }}
                >
                    <DialogContent>
                        {editing && (
                            <Form action={updateTransaction(editing.id)} resetOnSuccess onSuccess={() => {
                                setEditing(null);
                                setEditReceiptKey(null);
                                setEditFileMeta(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 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="cash-transaction"
                                                    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 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(),
        },
    ],
};
