"use client"

import FormDialog from "@/shared/components/form-dialog"
import { Badge } from "@/shared/components/ui/badge"
import { ResourcePage } from "@/shared/data-view/resource-page"
import { ColumnHeader } from "@/shared/data-view/table-view"
import { VendorCreditForm } from "@/modules/vendor-credits/vendor-credit-form"
import { VENDOR_CREDIT_ROUTES } from "@garage/api"
import type { VendorCreditsClient } from "@garage/api"

export default function VendorCreditsPage() {
    return (
        <ResourcePage<VendorCreditsClient>
            pageTitle="Vendor Credits"
            routeKey={VENDOR_CREDIT_ROUTES.INDEX}
            getClient={(api) => api.vendorCredits}
            headerProps={({ selectedItem, invalidateQuery }) => ({
                actions: (
                    <FormDialog title="Vendor Credit">
                        {(resourceId) => (
                            <VendorCreditForm
                                resourceId={resourceId}
                                initialData={selectedItem}
                                onSuccess={invalidateQuery}
                            />
                        )}
                    </FormDialog>
                ),
            })}
            columns={({ actionsColumn }) => [
                {
                    accessorKey: "subject",
                    header: ({ column }) => <ColumnHeader column={column} title="Subject" />,
                },
                {
                    accessorKey: "vendor_name",
                    header: ({ column }) => <ColumnHeader column={column} title="Vendor" />,
                    cell: ({ row }) => (row.original as any).vendor_name || "—",
                },
                {
                    accessorKey: "bill_number",
                    header: ({ column }) => <ColumnHeader column={column} title="Bill #" />,
                    cell: ({ row }) => (row.original as any).bill_number || "—",
                },
                {
                    accessorKey: "vendor_credit_date",
                    header: ({ column }) => <ColumnHeader column={column} title="Date" />,
                    cell: ({ row }) => {
                        const value = (row.original as any).vendor_credit_date
                        return value ? new Date(value).toLocaleDateString() : "—"
                    },
                },
                {
                    accessorKey: "status",
                    header: ({ column }) => <ColumnHeader column={column} title="Status" />,
                    cell: ({ row }) => {
                        const status = (row.original as any).status
                        return <Badge variant={status === "closed" ? "secondary" : "default"}>{status || "—"}</Badge>
                    },
                },
                actionsColumn(),
            ]}
        />
    )
}
