"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,
} 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 {
    purchaseOrderFormSchema,
    type PurchaseOrderFormValues,
} from "./purchase-order.schema"
import { PURCHASE_ORDER_ROUTES, VENDOR_ROUTES, JOB_CARD_ROUTES, DEPARTMENT_ROUTES } from "@garage/api"

// ── Props ──

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

// ── Default values ──

const DEFAULT_VALUES: PurchaseOrderFormValues = {
    vendor: null,
    job_card: null,
    department: null,
    title: "",
    order_date: "",
    delivery_date: "",
    notes: "",
}

// ── 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 || "",
        notes: d.notes || "",
    }
}

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,
        delivery_date: values.delivery_date || undefined,
        notes: values.notes || undefined,
    }
}

// ── Shared mapOption for async selects ──

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

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>
                <RhfTextField name="title" label="Title" placeholder="Enter purchase order title" required />

                <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                    <RhfTextField name="order_date" label="Order Date" placeholder="YYYY-MM-DD" type="date" />
                    <RhfTextField name="delivery_date" label="Delivery Date" placeholder="YYYY-MM-DD" type="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={mapLookupOption}
                        {...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.job_card_number || item.name || `#${item.id}`,
                    })}
                    {...STORE_OBJECT}
                />

                <RhfTextareaField name="notes" label="Notes" rows={3} />

                <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>
    )
}
