"use client"
import { CrudResource } from '@/shared/data-view/resource-page'
import { ColumnHeader } from '@/shared/data-view/table-view'
import { BadgeDollarSignIcon, CalendarIcon, ClipboardListIcon, CreditCardIcon, HashIcon, UserIcon } from 'lucide-react'
import { PAYMENT_RECEIVED_ROUTES } from '@garage/api'
import FormDialog from '@/shared/components/form-dialog'
import { PaymentReceivedForm } from '@/modules/payment-received/payment-received-form'
import { useInvoice } from './invoice-context'
import { Card, CardContent } from '@/shared/components/ui/card'
import { useRouter } from 'next/navigation'
export default function InvoicePaymentsSection() {
    const invoice = useInvoice()
    const router = useRouter()

    console.log("InvoicePaymentsSection invoice:", invoice)
    return (
        <div>
            <CrudResource<any>
                extraParams={{ invoice_id: invoice?.id }}
                routeKey={PAYMENT_RECEIVED_ROUTES.INDEX}
                getClient={(api) => ({
                    list: (query?: any) => api.paymentReceived.list(query),
                    destroy: (id: string) => api.paymentReceived.destroy(id),
                })}
                tableHeader={({ invalidateQuery }) =>
                    <Card className='mb-4'>
                        <CardContent className='flex justify-between '>
                            <h2>Payments</h2>
                            <FormDialog title="Record Payment">
                                {(resourceId) => {
                                    const invoiceJobCard =
                                        (invoice as any)?.jobCard ?? (invoice as any)?.job_card ?? null
                                    const invoiceJobCardId =
                                        invoiceJobCard?.id ?? (invoice as any)?.job_card_id ?? null
                                    const invoiceJobCardTitle =
                                        invoiceJobCard?.title ?? (invoice as any)?.job_card_name ?? null
                                    return (
                                        <PaymentReceivedForm
                                            invoiceId={invoice?.id as string}
                                            invoiceCustomer={
                                                (invoice?.customer as any) ??
                                                ((invoice as any)?.customer_id
                                                    ? {
                                                        id: (invoice as any).customer_id,
                                                        first_name: (invoice as any).customer_name,
                                                    }
                                                    : null)
                                            }
                                            invoiceAmount={invoice?.balance_due as any}
                                            defaultJobCard={
                                                invoiceJobCardId != null
                                                    ? { id: Number(invoiceJobCardId), title: invoiceJobCardTitle }
                                                    : null
                                            }
                                            lockJobCard={false}
                                            resourceId={resourceId}
                                            onSuccess={() => { router.refresh(); invalidateQuery() }}
                                        />
                                    )
                                }}
                            </FormDialog>

                        </CardContent>
                    </Card>
                }
                columns={({ actionsColumn }) => [
                    {
                        accessorKey: "payment_number",
                        header: ({ column }) => <ColumnHeader column={column} title="Payment #" />,
                        cell: ({ row }) => {
                            const item = row.original as any
                            return (
                                <div className="flex items-center gap-2">
                                    <HashIcon className="h-4 w-4 text-muted-foreground" />
                                    <span className="font-medium">{item.payment_number || "—"}</span>
                                </div>
                            )
                        },
                    },
                    {
                        accessorKey: "customer_name",
                        header: ({ column }) => <ColumnHeader column={column} title="Customer" />,
                        cell: ({ row }) => {
                            const item = row.original as any
                            return (
                                <div className="flex items-center gap-2">
                                    <UserIcon className="h-4 w-4 text-muted-foreground" />
                                    <span>{item.customer_name || "—"}</span>
                                </div>
                            )
                        },
                    },
                    {
                        accessorKey: "job_card_name",
                        header: ({ column }) => <ColumnHeader column={column} title="Job Card" />,
                        cell: ({ row }) => {
                            const item = row.original as any
                            const label = item.job_card_number || item.job_card_name
                            return (
                                <div className="flex items-center gap-2">
                                    <ClipboardListIcon className="h-4 w-4 text-muted-foreground" />
                                    <span>{label || "—"}</span>
                                </div>
                            )
                        },
                    },
                    {
                        accessorKey: "amount_received",
                        header: ({ column }) => <ColumnHeader column={column} title="Amount" />,
                        cell: ({ row }) => {
                            const item = row.original as any
                            const amount = item.amount_received
                                ? Number(item.amount_received).toLocaleString(undefined, {
                                    minimumFractionDigits: 2,
                                    maximumFractionDigits: 2,
                                })
                                : "—"
                            return (
                                <div className="flex items-center gap-2">
                                    <BadgeDollarSignIcon className="h-4 w-4 text-emerald-600" />
                                    <span className="font-semibold text-emerald-700 dark:text-emerald-400">
                                        {amount}
                                    </span>
                                </div>
                            )
                        },
                    },
                    {
                        accessorKey: "payment_mode",
                        header: ({ column }) => <ColumnHeader column={column} title="Payment Mode" />,
                        cell: ({ row }) => {
                            const item = row.original as any
                            return (
                                <div className="flex items-center gap-2">
                                    <CreditCardIcon className="h-4 w-4 text-muted-foreground" />
                                    <span className="capitalize">{item.payment_mode?.title || "—"}</span>
                                </div>
                            )
                        },
                    },
                    {
                        accessorKey: "payment_date",
                        header: ({ column }) => <ColumnHeader column={column} title="Date" />,
                        cell: ({ row }) => {
                            const item = row.original as any
                            const formatted = item.payment_date
                                ? new Date(item.payment_date).toLocaleDateString(undefined, {
                                    year: "numeric",
                                    month: "short",
                                    day: "numeric",
                                })
                                : "—"
                            return (
                                <div className="flex items-center gap-2">
                                    <CalendarIcon className="h-4 w-4 text-muted-foreground" />
                                    <span>{formatted}</span>
                                </div>
                            )
                        },
                    },
                    {
                        accessorKey: "note",
                        header: () => <span>Note</span>,
                        enableSorting: false,
                        cell: ({ row }) => {
                            const item = row.original as any
                            const note = item.note
                            if (!note) return <span className="text-muted-foreground">—</span>
                            return (
                                <span className="max-w-50 truncate block" title={note}>
                                    {note}
                                </span>
                            )
                        },
                    },
                    // actionsColumn(),
                ]}
            ></CrudResource>
        </div>
    )
}
