"use client"

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

import { Button } from "@/shared/components/ui/button"
import { Alert, AlertTitle } from "@/shared/components/ui/alert"
import { FieldGroup } from "@/shared/components/ui/field"
import {
    Rhform,
    RhfTextField,
    RhfSelectField,
    RhfTextareaField,
    RhfAsyncSelectField,
    RhfDateField,
    RhfAutoGenerateField,
} from "@/shared/components/form"
import { PartsSelectorField } from "@/modules/parts/parts-selector-field"
import { VendorForm } from "@/modules/vendors/vendor-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 {
    purchaseOrderFormSchema,
    type PurchaseOrderFormValues,
} from "./purchase-order.schema"
import { VENDOR_ROUTES, JOB_CARD_ROUTES, DEPARTMENT_ROUTES, InvoiceDiscount } from "@garage/api"
import { getFullName } from "@/shared/utils/getFullName"
import { useFormContext } from "react-hook-form"

// ── Props ──

export type PurchaseOrderFormProps = {
    resourceId?: string | null
    initialData?: unknown
    onSuccess?: () => void
}

// ── Default values ──

const DEFAULT_VALUES: PurchaseOrderFormValues = {
    vendor: null,
    order_number: "",
    job_card: null,
    department: null,
    title: "",
    order_date: new Date().toISOString().split("T")[0],
    delivery_date: "",
    notes: "",
    terms_and_conditions: "",
    discount_type: "no",
    discount_amount: undefined,
    label_ids: [],
    items: [],
}

// ── Mapping helpers ──

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

    return {
        vendor: toRelation(d.vendor_id, d.vendor_name),
        job_card: toRelation(d.job_card_id, d.job_card_name),
        department: toRelation(d.department_id, d.department_name),
        title: d.title || "",
        order_date: d.order_date || "",
        delivery_date: d.delivery_date || "",
        order_number: d.order_number || "" as any,
        notes: d.notes || "",
        terms_and_conditions: d.terms_and_conditions || "",
        discount_type: d.discount_type || "no",
        discount_amount: d.discount_amount != null ? Number(d.discount_amount) : undefined,
        label_ids: Array.isArray(d.label_ids) ? d.label_ids.map((id: any) => Number(id)).filter((id: number) => Number.isFinite(id)) : [],
        items: (d.parts ?? d.items ?? []).map((p: any) => ({
            part_id: p.part_id ?? p.id,
            title: p.part?.title ?? p.title ?? "",
            quantity: p.quantity ?? 1,
            rate: Number(p.rate) || 0,
            description: p.description ?? "",
        })),
    }
}

function mapFormToPayload(values: PurchaseOrderFormValues) {
    return {
        vendor_id: toId(values.vendor),
        job_card_id: toId(values.job_card),
        department_id: toId(values.department),
        title: values.title,
        order_date: values.order_date || undefined,
        order_number: values.order_number,
        delivery_date: values.delivery_date || undefined,
        notes: values.notes || undefined,
        terms_and_conditions: values.terms_and_conditions || undefined,
        discount_type: values.discount_type || undefined,
        discount_amount: values.discount_type === "transaction_level" ? (values.discount_amount ?? 0) : undefined,
        label_ids: values.label_ids?.length ? values.label_ids : undefined,
        items: (values.items ?? []).map((item) => ({
            part_id: item.part_id,
            quantity: item.quantity,
            rate: item.rate,
            description: item.description || undefined,
        })),
    }
}

const DISCOUNT_OPTIONS = InvoiceDiscount.map((v) => ({
    value: v,
    label: v.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase()),
}))

function TransactionDiscountField() {
    const { watch } = useFormContext<PurchaseOrderFormValues>()
    const discount = watch("discount_type")

    if (discount !== "transaction_level") return null

    return (
        <RhfTextField
            name="discount_amount"
            label="Discount Amount"
            type="number"
            placeholder="0.00"
        />
    )
}

// ── Shared mapOption for async selects ──

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

const getVendorLabel = (item: any) => getFullName(item) || item.company_name || item.name || `#${item.id}`

const mapVendorOption = (item: any) => ({
    value: String(item.id),
    label: getVendorLabel(item),
})

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

// ── Component ──

export function PurchaseOrderForm({ resourceId, initialData, onSuccess }: PurchaseOrderFormProps) {
    const api = useAuthApi()

    const { form, isEditing } = useResourceForm<PurchaseOrderFormValues, any>({
        schema: purchaseOrderFormSchema,
        defaultValues: DEFAULT_VALUES,
        resourceId,
        initialData,
        mapToFormValues,
    })

    const { mutate, error, isPending } = useFormMutation(form, {
        mutationFn: (values: PurchaseOrderFormValues) => {
            const payload = mapFormToPayload(values)
            const promise = isEditing && resourceId
                ? api.purchaseOrders.update(resourceId, payload)
                : api.purchaseOrders.create(payload)
            toast.promise(promise, {
                loading: isEditing ? "Updating purchase order..." : "Creating purchase order...",
                success: isEditing ? "Purchase order updated successfully" : "Purchase order created successfully",
                error: isEditing ? "Failed to update purchase order" : "Failed to create purchase order",
            })
            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 purchase order" : "Failed to create purchase order"}
                    </AlertTitle>
                    {error.message}
                </Alert>
            )}

            <FieldGroup>

                <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                    <RhfTextField name="title" label="Title" placeholder="Enter purchase order title" />
                    <RhfAutoGenerateField autoFetch table="purchase-order" name="order_number" label="Order Number" placeholder="Enter purchase order number" required />
                    <RhfDateField name="order_date" label="Order Date" />
                    <RhfDateField name="delivery_date" label="Delivery Date" />
                </div>

                <RhfSelectField
                    name="discount_type"
                    label="Discount Type"
                    placeholder="Select discount type"
                    options={DISCOUNT_OPTIONS}
                />

                <TransactionDiscountField />

                <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                    <RhfAsyncSelectField
                        name="vendor"
                        label="Vendor"
                        placeholder="Select vendor"
                        required
                        queryKey={[VENDOR_ROUTES.INDEX]}
                        listFn={() => api.vendors.list()}
                        mapOption={mapVendorOption}
                        createForm={({ onSuccess }) => (
                            <VendorForm
                                onSuccess={(data) => {
                                    const vendor = (data as any)?.data ?? data
                                    onSuccess(vendor?.id ? mapVendorOption(vendor) : undefined)
                                }}
                            />
                        )}
                        createLabel="Vendor"
                        {...STORE_OBJECT}
                    />
                    <RhfAsyncSelectField
                        name="department"
                        label="Department"
                        placeholder="Select department"
                        required
                        queryKey={[DEPARTMENT_ROUTES.INDEX]}
                        listFn={() => api.departments.list()}
                        mapOption={mapLookupOption}
                        {...STORE_OBJECT}
                    />
                </div>

                <RhfAsyncSelectField
                    name="job_card"
                    label="Job Card"
                    placeholder="Select job card"
                    required
                    queryKey={[JOB_CARD_ROUTES.INDEX]}
                    listFn={() => api.jobCards.list()}
                    mapOption={(item: any) => ({
                        value: String(item.id),
                        label: item.title || `#${item.id}`,
                    })}
                    {...STORE_OBJECT}
                />

                <RhfTextareaField name="notes" label="Notes" rows={3} />
                <RhfTextareaField name="terms_and_conditions" label="Terms & Conditions" rows={3} />

                <PartsSelectorField<PurchaseOrderFormValues, "items"> name="items" />

                <Button type="submit" variant="default" disabled={isPending}>
                    {isPending ? (
                        "Saving..."
                    ) : isEditing ? (
                        <>
                            <Save className="me-2 h-4 w-4" />
                            Update Purchase Order
                        </>
                    ) : (
                        <>
                            <Plus className="me-2 h-4 w-4" />
                            Create Purchase Order
                        </>
                    )}
                </Button>
            </FieldGroup>
        </Rhform>
    )
}
