import { Head, router } from '@inertiajs/react';
import { ArrowDownToLine, ArrowUpFromLine, Wallet } from 'lucide-react';
import { useState } from 'react';
import type { PaginationState } from '@/components/data-display';
import { DataTable } from '@/components/data-display';
import { DeleteConfirmDialog } from '@/components/dialogs';
import { FileUpload } from '@/components/inputs';
import { FilterPopover } from '@/components/data-display';
import { FormDialog } from '@/components/dialogs';
import { InputError } from '@/components/ui';
import { PageHeader } from '@/components/layout';
import { RupiahInput } from '@/components/inputs';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { useCan } from '@/hooks/use-can';
import { useServerTable } from '@/hooks/use-server-table';
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 TypeOption = {
    value: string;
    label: string;
};

type Props = {
    cashAccount: CashAccount | null;
    transactions: {
        data: CashTransaction[];
        current_page: number;
        last_page: number;
        per_page: number;
        total: number;
    };
    filters: {
        type?: string;
    };
    filterOptions: {
        typeOptions: TypeOption[];
    };
};

export default function CashAccountIndex({
    cashAccount,
    transactions,
    filters,
    filterOptions,
}: Props) {
    const { can } = useCan();
    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 [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 pagination: PaginationState = {
        current_page: transactions.current_page,
        last_page: transactions.last_page,
        per_page: transactions.per_page,
        total: transactions.total,
    };

    const {
        search,
        filterOpen,
        setFilterOpen,
        handlePageChange,
        handlePerPageChange,
        handleSearchChange,
        applyFilter,
        clearFilters,
    } = useServerTable({
        route: () => cashAccountIndex.url(),
        pagination,
        filters,
    });

    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),
        can,
    });

    const filterToolbar = (
        <FilterPopover
            open={filterOpen}
            onOpenChange={setFilterOpen}
            filters={filters}
            hasActiveFilters={Boolean(filters.type)}
            onClear={clearFilters}
        >
            <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>
                        {filterOptions.typeOptions.map((opt) => (
                            <SelectItem key={opt.value} value={opt.value}>
                                {opt.label}
                            </SelectItem>
                        ))}
                    </SelectContent>
                </Select>
            </div>
        </FilterPopover>
    );

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

            <div className="flex h-full flex-1 flex-col gap-6 overflow-x-auto p-4 md:p-6">
                <PageHeader
                    title="Kas Toko"
                    actions={
                        <div className="flex items-center gap-2">
                            {can('cash.deposit') && (
                                <Button
                                    variant="outline"
                                    onClick={() => setDepositOpen(true)}
                                >
                                    <ArrowDownToLine className="h-4 w-4" />
                                    Deposit
                                </Button>
                            )}
                            {can('cash.withdraw') && (
                                <Button
                                    variant="outline"
                                    onClick={() => setWithdrawalOpen(true)}
                                >
                                    <ArrowUpFromLine className="h-4 w-4" />
                                    Withdrawal
                                </Button>
                            )}
                        </div>
                    }
                />

                <Card className="overflow-visible">
                    <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.data}
                    searchKey="description"

                    emptyText="Belum ada riwayat transaksi."
                    pagination={pagination}
                    onPageChange={handlePageChange}
                    onPerPageChange={handlePerPageChange}
                    onSearchChange={handleSearchChange}
                    searchValue={search}
                    toolbar={filterToolbar}
                />

                <FormDialog
                    open={depositOpen}
                    onOpenChange={(open) => {
                        setDepositOpen(open);

                        if (!open) {
                            setDepositReceiptKey(null);
                            setDepositFileMeta(null);
                        }
                    }}
                    title="Deposit"
                    action={deposit()}
                    resetOnSuccess
                    onSuccess={() => {
                        setDepositOpen(false);
                        setDepositReceiptKey(null);
                        setDepositFileMeta(null);
                    }}
                    submitDisabled={depositUploading}
                    submitLabel={depositUploading ? 'Mengunggah...' : 'Simpan'}
                >
                    {({ errors }) => (
                        <>
                            <div className="grid gap-2">
                                <Label>
                                    Jumlah{' '}
                                    <span className="text-destructive">*</span>
                                </Label>
                                <RupiahInput name="amount" />
                                <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>
                        </>
                    )}
                </FormDialog>

                <FormDialog
                    open={withdrawalOpen}
                    onOpenChange={(open) => {
                        setWithdrawalOpen(open);

                        if (!open) {
                            setWithdrawalReceiptKey(null);
                            setWithdrawalFileMeta(null);
                        }
                    }}
                    title="Withdrawal"
                    action={withdrawal()}
                    resetOnSuccess
                    onSuccess={() => {
                        setWithdrawalOpen(false);
                        setWithdrawalReceiptKey(null);
                        setWithdrawalFileMeta(null);
                    }}
                    submitDisabled={withdrawalUploading}
                    submitLabel={
                        withdrawalUploading ? 'Mengunggah...' : 'Simpan'
                    }
                >
                    {({ errors }) => (
                        <>
                            <div className="grid gap-2">
                                <Label>
                                    Jumlah{' '}
                                    <span className="text-destructive">*</span>
                                </Label>
                                <RupiahInput name="amount" />
                                <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>
                        </>
                    )}
                </FormDialog>

                <FormDialog
                    open={editing !== null}
                    onOpenChange={(open) => {
                        if (!open) {
                            setEditing(null);
                            setEditReceiptKey(null);
                            setEditFileMeta(null);
                        }
                    }}
                    title="Edit Transaksi"
                    action={editing ? updateTransaction(editing.id) : ''}
                    resetOnSuccess
                    onSuccess={() => {
                        setEditing(null);
                        setEditReceiptKey(null);
                        setEditFileMeta(null);
                    }}
                    submitDisabled={editUploading}
                    submitLabel={editUploading ? 'Mengunggah...' : 'Simpan'}
                >
                    {({ errors }) =>
                        editing && (
                            <>
                                <div className="grid gap-2">
                                    <Label>
                                        Jumlah{' '}
                                        <span className="text-destructive">
                                            *
                                        </span>
                                    </Label>
                                    <RupiahInput
                                        name="amount"
                                        defaultValue={editing.amount}
                                    />
                                    <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>
                            </>
                        )
                    }
                </FormDialog>

                <DeleteConfirmDialog
                    target={deleting}
                    onOpenChange={(open) => {
                        if (!open) {
                            setDeleting(null);
                        }
                    }}
                    title="Hapus Transaksi"
                    description={(transaction) =>
                        `Apakah Anda yakin ingin menghapus transaksi "${transaction.description}"? Tindakan ini tidak dapat dibatalkan.`
                    }
                    onConfirm={handleDelete}
                />
            </div>
        </>
    );
}
