"use client"

import { useMemo } from "react"
import { AlertTriangle, Plus, Save } from "lucide-react"

import { Button } from "@/shared/components/ui/button"
import { Alert, AlertTitle } from "@/shared/components/ui/alert"
import { Field, FieldGroup, FieldLabel } from "@/shared/components/ui/field"
import { Input } from "@/shared/components/ui/input"
import {
    Rhform,
    RhfTextField,
    RhfTextareaField,
    RhfAsyncSelectField,
    RhfDateField,
    RhfAutoGenerateField,
} from "@/shared/components/form"
import { toast } from "sonner"
import { useAuthApi } from "@/shared/useApi"
import { useResourceForm } from "@/shared/hooks/use-resource-form"
import { useFormMutation } from "@/shared/hooks/use-form-mutation"
import { toRelation, toId } from "@/shared/lib/utils"

import {
    paymentReceivedFormSchema,
    type PaymentReceivedFormValues,
} from "./payment-received.schema"
import { PAYMENT_MODE_ROUTES, CUSTOMER_ROUTES, JOB_CARD_ROUTES, INVOICE_ROUTES, PAYMENT_RECEIVED_ROUTES } from "@garage/api"

// ── Props ──

export type PaymentReceivedFormProps = {
    resourceId?: string | null
    initialData?: unknown
    onSuccess?: () => void
    defaultJobCard?: { id?: number | null; title?: string | null } | null
    invoiceId?: string | null
    invoiceCustomer?: { id?: number | null; first_name?: string | null; last_name?: string | null } | null
    invoiceAmount?: number | string | null
    lockJobCard?: boolean
    lockCustomer?: boolean
}

// ── Default values ──

const DEFAULT_VALUES: PaymentReceivedFormValues = {
    job_card: null,
    invoice: null,
    payment_mode: null,
    customer: null,
    amount_received: 0,
    payment_number: "",
    payment_date: new Date().toISOString().split("T")[0],
    note: "",
}

// ── Mapping helpers ──

function mapToFormValues(data: unknown): PaymentReceivedFormValues {
    const d = (data as any)?.data ?? data ?? {}

    const jobCardId = d.job_card_id ?? d.job_card?.id
    const jobCardLabel = d.job_card?.title ?? d.job_card_name

    const invoiceId = d.invoice_id ?? d.invoice?.id
    const invoiceLabel = d.invoice?.invoice_number ?? d.invoice?.title ?? d.invoice_number

    const paymentModeId = d.payment_mode_id ?? d.payment_mode?.id
    const paymentModeLabel = d.payment_mode?.title ?? d.payment_mode?.name ?? d.payment_mode_name

    const customerId = d.customer_id ?? d.customer?.id
    const customerLabel = d.customer?.first_name
        ? `${d.customer.first_name} ${d.customer.last_name ?? ""}`.trim()
        : d.customer?.company_name ?? d.customer?.name ?? d.customer_name

    const rawDate = d.payment_date
    const payment_date = typeof rawDate === "string" && rawDate
        ? rawDate.slice(0, 10)
        : new Date().toISOString().split("T")[0]

    return {
        job_card: toRelation(jobCardId, jobCardLabel),
        invoice: toRelation(invoiceId, invoiceLabel),
        payment_mode: toRelation(paymentModeId, paymentModeLabel),
        customer: toRelation(customerId, customerLabel),
        amount_received: d.amount_received != null ? Number(d.amount_received) : 0,
        payment_number: d.payment_number || "",
        payment_date,
        note: d.note || "",
    }
}

function mapFormToPayload(values: PaymentReceivedFormValues, invoiceId?: string | null) {
    // Prefer the invoice the form was opened from; otherwise the one picked in
    // the standalone form. Linking invoice_id is what flips the invoice to Paid.
    const resolvedInvoiceId = invoiceId ?? toId(values.invoice)
    return {
        job_card_id: toId(values.job_card),
        payment_mode_id: toId(values.payment_mode),
        customer_id: toId(values.customer),
        amount_received: values.amount_received,
        payment_number: values.payment_number || undefined,
        payment_date: values.payment_date,
        note: values.note || undefined,
        ...(resolvedInvoiceId ? { invoice_id: Number(resolvedInvoiceId) } : {}),
    }
}

// ── Shared mapOption for async selects ──

const mapLookupOption = (item: any) => ({
    value: String(item.id),
    label: item.name || item.title,
})

const STORE_OBJECT = { getOptionValue: (o: any) => o, getOptionLabel: (o: any) => o.label }

// ── Component ──

export function PaymentReceivedForm({ resourceId, initialData, onSuccess, defaultJobCard, invoiceId, invoiceCustomer, invoiceAmount, lockJobCard, lockCustomer }: PaymentReceivedFormProps) {
    const api = useAuthApi()

    const isJobCardLocked = !resourceId && (lockJobCard ?? !!defaultJobCard?.id)
    const isCustomerLocked = !resourceId && (lockCustomer ?? !!invoiceCustomer?.id)
    // When opened from a specific invoice the link is implicit (invoiceId prop).
    // Standalone (Payments Received → Add) needs a picker so the payment can be
    // tied to an invoice — otherwise the invoice never shows as Paid.
    const showInvoiceField = !invoiceId

    const customerLabel = invoiceCustomer?.first_name
        ? `${invoiceCustomer.first_name} ${invoiceCustomer.last_name || ""}`.trim()
        : (invoiceCustomer as any)?.company_name || (invoiceCustomer as any)?.name || ""

    const resolvedInitialData = useMemo(() => {
        const base: any = { ...(initialData as any) }
        if (!resourceId) {
            if (defaultJobCard?.id != null) {
                base.job_card_id = defaultJobCard.id
                base.job_card_name = defaultJobCard.title ?? undefined
            }
            if (invoiceCustomer?.id != null) {
                base.customer_id = invoiceCustomer.id
                base.customer_name = customerLabel
            }
            if (invoiceAmount != null && invoiceAmount !== "") {
                base.amount_received = Number(invoiceAmount)
            }
        }
        return Object.keys(base).length ? base : initialData
    }, [resourceId, defaultJobCard, initialData, invoiceCustomer, invoiceAmount, customerLabel])

    const { form, isEditing } = useResourceForm<PaymentReceivedFormValues, any>({
        schema: paymentReceivedFormSchema,
        defaultValues: DEFAULT_VALUES,
        resourceId,
        initialData: resolvedInitialData,
        initialize: (id) => api.paymentReceived.show(id),
        queryKey: [PAYMENT_RECEIVED_ROUTES.BY_ID, resourceId],
        mapToFormValues,
    })

    const { mutate, error, isPending } = useFormMutation(form, {
        mutationFn: (values: PaymentReceivedFormValues) => {
            const payload = mapFormToPayload(values, invoiceId)
            const promise = isEditing && resourceId
                ? api.paymentReceived.update(resourceId, payload as any)
                : api.paymentReceived.create(payload as any)
            toast.promise(promise, {
                loading: isEditing ? "Updating payment..." : "Recording payment...",
                success: isEditing ? "Payment updated successfully" : "Payment recorded successfully",
                error: isEditing ? "Failed to update payment" : "Failed to record payment",
            })
            return promise
        },
        onSuccess: () => {
            form.reset()
            onSuccess?.()
        },
    })

    return (
        <Rhform form={form} onSubmit={(values) => mutate(values)}>
            {error && (
                <Alert variant="destructive" className="mb-4">
                    <AlertTriangle className="me-2 h-4 w-4" />
                    <AlertTitle>
                        {isEditing ? "Failed to update payment" : "Failed to record payment"}
                    </AlertTitle>
                    {error.message}
                </Alert>
            )}

            <FieldGroup>
                <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                    {isCustomerLocked ? (
                        <Field>
                            <FieldLabel>
                                Customer<span className="text-destructive ms-0.5">*</span>
                            </FieldLabel>
                            <Input value={customerLabel} readOnly disabled />
                        </Field>
                    ) : (
                        <RhfAsyncSelectField
                            name="customer"
                            label="Customer"
                            placeholder="Select customer"
                            required
                            queryKey={[CUSTOMER_ROUTES.INDEX]}
                            listFn={() => api.customers.list()}
                            mapOption={(item: any) => ({
                                value: String(item.id),
                                label: item.first_name
                                    ? `${item.first_name} ${item.last_name || ""}`.trim()
                                    : item.name || `#${item.id}`,
                            })}
                            {...STORE_OBJECT}
                        />
                    )}
                    {isJobCardLocked ? (
                        <Field>
                            <FieldLabel>Job Card</FieldLabel>
                            <Input value={defaultJobCard?.title ?? ""} readOnly disabled />
                        </Field>
                    ) : (
                        <RhfAsyncSelectField
                            name="job_card"
                            label="Job Card"
                            placeholder="Select job card"
                            queryKey={[JOB_CARD_ROUTES.INDEX]}
                            listFn={() => api.jobCards.list()}
                            mapOption={(item: any) => ({
                                value: String(item.id),
                                label: item.title,
                            })}
                            {...STORE_OBJECT}
                        />
                    )}
                </div>

                {showInvoiceField && (
                    <RhfAsyncSelectField
                        name="invoice"
                        label="Invoice"
                        placeholder="Select invoice to mark as paid"
                        description="Link this payment to an invoice so it is marked paid."
                        queryKey={[INVOICE_ROUTES.INDEX]}
                        listFn={() => api.invoices.list()}
                        mapOption={(item: any) => ({
                            value: String(item.id),
                            label: item.invoice_number ?? item.title ?? `#${item.id}`,
                        })}
                        {...STORE_OBJECT}
                    />
                )}

                <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                    <RhfTextField
                        name="amount_received"
                        label="Amount Received"
                        placeholder="0.00"
                        type="number"
                        required
                    />
                    <RhfAsyncSelectField
                        name="payment_mode"
                        label="Payment Mode"
                        placeholder="Select payment mode"
                        required
                        queryKey={[PAYMENT_MODE_ROUTES.INDEX]}
                        listFn={() => api.paymentModes.list()}
                        mapOption={mapLookupOption}
                        {...STORE_OBJECT}
                    />
                </div>

                <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                    <RhfAutoGenerateField
                        autoFetch
                        table="payments"
                        name="payment_number"
                        label="Payment Number"
                        placeholder="PAY-001"
                    />
                    <RhfDateField
                        name="payment_date"
                        label="Payment Date"
                    />
                </div>

                <RhfTextareaField name="note" label="Note" rows={3} placeholder="Add any notes about this payment..." />

                <Button type="submit" variant="default" disabled={isPending}>
                    {isEditing ? <Save /> : <Plus />}
                    {isPending
                        ? (isEditing ? "Updating..." : "Recording...")
                        : (isEditing ? "Update Payment" : "Record Payment")}
                </Button>
            </FieldGroup>
        </Rhform>
    )
}
