import { Head, router } from '@inertiajs/react';
import { Plus } 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 { 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 { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useCan } from '@/hooks/use-can';
import { useServerTable } from '@/hooks/use-server-table';
import {
    destroy,
    index as expenseIndex,
    store,
    update,
} from '@/routes/admin/finance/expenses';
import { createExpenseColumns } from './columns';
import type { Expense } from './columns';

type Props = {
    expenses: {
        data: Expense[];
        current_page: number;
        last_page: number;
        per_page: number;
        total: number;
    };
};

export default function ExpenseIndex({ expenses }: Props) {
    const { can } = useCan();
    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);

    const pagination: PaginationState = {
        current_page: expenses.current_page,
        last_page: expenses.last_page,
        per_page: expenses.per_page,
        total: expenses.total,
    };

    const {
        search,
        handlePageChange,
        handlePerPageChange,
        handleSearchChange,
    } = useServerTable({
        route: () => expenseIndex.url(),
        pagination,
    });

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

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

            <div className="flex h-full flex-1 flex-col gap-6 overflow-x-auto p-4 md:p-6">
                <PageHeader
                    title="Pengeluaran"
                    actions={
                        can('expenses.create') ? (
                            <Button asChild>
                                <button
                                    type="button"
                                    onClick={() => setCreateOpen(true)}
                                >
                                    <Plus className="h-4 w-4" />
                                    Tambah
                                </button>
                            </Button>
                        ) : undefined
                    }
                />

                <FormDialog
                    open={createOpen}
                    onOpenChange={(open) => {
                        setCreateOpen(open);

                        if (!open) {
                            setCreateReceiptKey(null);
                            setCreateFileMeta(null);
                        }
                    }}
                    title="Tambah Pengeluaran"
                    action={store()}
                    resetOnSuccess
                    onSuccess={() => {
                        setCreateOpen(false);
                        setCreateReceiptKey(null);
                        setCreateFileMeta(null);
                    }}
                    submitDisabled={createUploading}
                    submitLabel={createUploading ? '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 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>
                        </>
                    )}
                </FormDialog>

                <FormDialog
                    open={editing !== null}
                    onOpenChange={(open) => {
                        if (!open) {
                            setEditing(null);
                            setEditReceiptKey(null);
                            setEditFileMeta(null);
                        }
                    }}
                    title="Edit Pengeluaran"
                    action={editing ? update(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 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>
                            </>
                        )
                    }
                </FormDialog>

                <DataTable
                    columns={columns}
                    data={expenses.data}
                    searchKey="description"

                    emptyText="Belum ada data pengeluaran."
                    pagination={pagination}
                    onPageChange={handlePageChange}
                    onPerPageChange={handlePerPageChange}
                    onSearchChange={handleSearchChange}
                    searchValue={search}
                />

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