"use client"

import { useQueryClient } from "@tanstack/react-query"
import { CrudResource } from "@/shared/data-view/resource-page"
import { ColumnHeader } from "@/shared/data-view/table-view"
import FormDialog from "@/shared/components/form-dialog"
import { PaymentReceivedForm } from "@/modules/payment-received/payment-received-form"
import { PAYMENT_RECEIVED_ROUTES, PaymentReceivedClient } from "@garage/api"
import {
    BadgeDollarSignIcon,
    CalendarIcon,
    ChevronDown,
    CreditCardIcon,
    HashIcon,
} from "lucide-react"
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/shared/components/ui/collapsible"
import { Button } from "@/shared/components/ui/button"
import { useJobCard } from "./job-card-context"
import { formatDate } from "@/shared/utils/formatters"
import { useState } from "react"
import { Money } from "@/shared/components/money"

export default function JobCardPaymentsReceived() {
    const jobCard = useJobCard()
    const queryClient = useQueryClient()
    const [hasOpened, setHasOpened] = useState(false)

    return (
        <Collapsible
            defaultOpen={false}
            className="group/collapsible"
            onOpenChange={(open) => {
                if (open) setHasOpened(true)
            }}
        >
            <Card>
                <CardHeader>
                    <div className="flex items-center justify-between">
                        <CardTitle className="text-sm font-semibold">Payments Received</CardTitle>
                        <CollapsibleTrigger asChild>
                            <Button variant="ghost" size="icon" className="h-7 w-7">
                                <ChevronDown className="h-4 w-4 transition-transform duration-200 group-data-[state=open]/collapsible:rotate-180" />
                            </Button>
                        </CollapsibleTrigger>
                    </div>
                </CardHeader>
                <CollapsibleContent>
                    <CardContent className="pt-0">
                        {hasOpened && (
                        <CrudResource<PaymentReceivedClient>
                            extraParams={{ job_card_id: jobCard?.id }}
                            routeKey={PAYMENT_RECEIVED_ROUTES.INDEX}
                            getClient={(api) => api.paymentReceived}
                            tableHeader={({ invalidateQuery }) =>
                                <div className="p-2">
                                    <FormDialog title="Record Payment">
                                        {(resourceId) => (
                                            <PaymentReceivedForm
                                                resourceId={resourceId}
                                                defaultJobCard={{ id: jobCard?.id, title: jobCard?.title }}
                                                invoiceCustomer={jobCard?.customer as any}
                                                lockJobCard
                                                lockCustomer
                                                onSuccess={() => {
                                                    // Refresh the payments list AND the job card / invoice
                                                    // queries so the PAID status reflects the new payment.
                                                    invalidateQuery()
                                                    queryClient.invalidateQueries()
                                                }}
                                            />
                                        )}
                                    </FormDialog>
                                </div>
                            }
                            columns={({ actionsColumn }) => [
                                {
                                    accessorKey: "payment_number",
                                    header: ({ column }) => <ColumnHeader column={column} title="Payment #" />,
                                    cell: ({ row }) => {
                                        const item = row.original
                                        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: "amount_received",
                                    header: ({ column }) => <ColumnHeader column={column} title="Amount" />,
                                    cell: ({ row }) => {
                                        const item = row.original
                                        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">
                                                    {<Money value={item.amount_received} />}
                                                </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
                                        return (
                                            <div className="flex items-center gap-2">
                                                <CalendarIcon className="h-4 w-4 text-muted-foreground" />
                                                <span>{formatDate(item.payment_date)}</span>
                                            </div>
                                        )
                                    },
                                },
                                {
                                    accessorKey: "note",
                                    header: () => <span>Note</span>,
                                    enableSorting: false,
                                    cell: ({ row }) => {
                                        const item = row.original
                                        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(),
                            ]}
                        />
                        )}
                    </CardContent>
                </CollapsibleContent>
            </Card>
        </Collapsible>
    )
}
