"use client"

import { useQuery } from "@tanstack/react-query"
import { useAuthApi } from "@/shared/useApi"
import { INVOICE_ROUTES, type InvoiceShowData } from "@garage/api"
import { toRelation } from "@/shared/lib/utils"
import FormDialog from "@/shared/components/form-dialog"
import { PaymentReceivedForm } from "@/modules/payment-received/payment-received-form"

type InvoicePaymentButtonProps = {
    invoiceId: string
    onSuccess?: () => void
}

function toTodayString() {
    return new Date().toISOString().split("T")[0]!
}

export function InvoicePaymentButton({ invoiceId, onSuccess }: InvoicePaymentButtonProps) {
    const api = useAuthApi()

    const { data } = useQuery({
        queryKey: [INVOICE_ROUTES.BY_ID, invoiceId],
        queryFn: () => api.invoices.show(invoiceId),
    })

    const invoice = data?.data

    const total = parseFloat(String(invoice?.amount ?? 0)) || 0
    const paid = parseFloat(String(invoice?.received_payment ?? 0)) || 0
    const balanceDue = Math.max(0, total - paid)

    const customer = invoice?.customer || {}
    const customerLabel = customer.first_name
        ? `${customer.first_name} ${customer.last_name ?? ""}`.trim()
        : invoice?.customer_name ?? undefined

    const prefilledInitialData = {
        ...(invoice?.customer_id
            ? { customer: toRelation(invoice?.customer_id, customerLabel) }
            : {}),
        amount_received: balanceDue > 0 ? String(balanceDue) : "",
        payment_date: toTodayString(),
    }

    return (
        <FormDialog title="Record Payment" paramKey="invoice-payment">
            {(resourceId, { close }) => (
                <PaymentReceivedForm
                    resourceId={resourceId}
                    initialData={prefilledInitialData}
                    invoiceId={invoiceId}
                    onSuccess={() => {
                        close()
                        onSuccess?.()
                    }}
                />
            )}
        </FormDialog>
    )
}
