"use client"

import { ResourcePage } from "@/shared/data-view/resource-page"
import { ColumnHeader } from "@/shared/data-view/table-view"
import FormDialog from "@/shared/components/form-dialog"
import { ExpenseForm } from "@/modules/expenses/expense-form"
import { Badge } from "@/shared/components/ui/badge"
import { EXPENSE_ROUTES, ExpenseStatus } from "@garage/api"
import type { ExpensesClient } from "@garage/api"
import { useRouter } from "next/navigation"
import { formatDate, formatEnum } from "@/shared/utils/formatters"
import { Money } from "@/shared/components/money"
import { RelationLink } from "@/shared/components/relation-link"
import { Building2, Printer } from "lucide-react"
import { getFullName } from "@/shared/utils/getFullName"
import { useDocumentPrint } from "@/shared/hooks/use-document-print"

export default function ExpensesPage() {
    const router = useRouter()
    const { print, isPrinting } = useDocumentPrint()
    return (
        <ResourcePage<ExpensesClient>
            pageTitle="Expenses"
            routeKey={EXPENSE_ROUTES.INDEX}
            searchable
            searchPlaceholder="Search expenses..."
            statusFilter={{ statuses: ExpenseStatus }}
            getClient={(api) => api.expenses}
            onRowClick={(row)=>router.push(`/purchase/expense/${row.id}`)}
            headerProps={({ selectedItem, invalidateQuery }) => ({
                actions: (
                    <FormDialog
                        title="Expense"
                        classNames={{ dialogContent: "lg:min-w-6xl" }}
                    >
                        {(resourceId) => (
                            <ExpenseForm
                                resourceId={resourceId}
                                initialData={selectedItem}
                                onSuccess={invalidateQuery}
                            />
                        )}
                    </FormDialog>
                ),
            })}
            columns={({ actionsColumn }) => [
                {
                    accessorKey: "title",
                    header: ({ column }) => <ColumnHeader column={column} title="Title" />,
                },
                {
                    accessorKey: "invoice_number",
                    header: ({ column }) => <ColumnHeader column={column} title="Invoice #" />,
                    cell: ({ row }) => (row.original as any).invoice_number || "—",
                },
                {
                    accessorKey: "vendor",
                    header: () => "Vendor",
                    cell: ({ row }) => {
                        const vendor = (row.original as any).vendor
                        return (
                            <RelationLink
                                href={vendor?.id ? `/purchase/vendor/${vendor.id}` : null}
                                icon={Building2}
                                label={vendor?.company_name || getFullName(vendor) || vendor?.name}
                            />
                        )
                    },
                },
                {
                    accessorKey: "expense_date",
                    header: ({ column }) => <ColumnHeader column={column} title="Date" />,
                    cell: ({ row }) => formatDate((row.original as any).expense_date),
                },
                {
                    accessorKey: "total",
                    header: () => "Total",
                    cell: ({ row }) => <Money value={(row.original as any).total ?? 0} />,
                },
                {
                    accessorKey: "balance_due",
                    header: () => "Balance Due",
                    cell: ({ row }) => <Money value={(row.original as any).balance_due ?? 0} />,
                },
                {
                    accessorKey: "status",
                    header: ({ column }) => <ColumnHeader column={column} title="Status" />,
                    cell: ({ row }) => {
                        const status = (row.original as any).status
                        const variantMap: Record<string, "default" | "secondary" | "destructive" | "outline"> = {
                            draft: "secondary",
                            open: "default",
                            un_paid: "destructive",
                            partially_paid: "secondary",
                            paid: "default",
                        }
                        return (
                            <Badge variant={variantMap[status] ?? "outline"}>
                                {formatEnum(status) || "—"}
                            </Badge>
                        )
                    },
                },
                actionsColumn({
                    extraItems: (row) => [
                        {
                            label: isPrinting ? "Printing..." : "Print",
                            icon: Printer,
                            onClick: (r) => print("expense", String(r.id), "print"),
                        },
                    ],
                }),
            ]}
        />
    )
}
