"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,
    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 } from "@garage/api"
import { getFullName } from "@/shared/utils/getFullName"

// ── 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: "",
    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 || "",
        items: (d.parts ?? []).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,
        items: (values.items ?? []).map((item) => ({
            part_id: item.part_id,
            quantity: item.quantity,
            rate: item.rate,
            description: item.description || undefined,
        })),
    }
}

// ── 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" required />
                    <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>

                <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                    <RhfAsyncSelectField
                        name="vendor"
                        label="Vendor"
                        placeholder="Select vendor"
                        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"
                        queryKey={[DEPARTMENT_ROUTES.INDEX]}
                        listFn={() => api.departments.list()}
                        mapOption={mapLookupOption}
                        {...STORE_OBJECT}
                    />
                </div>

                <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 || `#${item.id}`,
                    })}
                    {...STORE_OBJECT}
                />

                <RhfTextareaField name="notes" label="Notes" 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>
    )
}
