"use client"

import { useEffect, useRef } from "react"
import { useFormContext, useWatch } from "react-hook-form"
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,
    RhfSelectField,
    RhfAsyncSelectField,
    RhfDateField,
    RhfTimeField,
} 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 { InspectionCategoryInlineForm } from "./inline-forms/inspection-category-inline-form"
import { DepartmentInlineForm } from "@/modules/services/inline-forms/department-inline-form"

import {
    inspectionFormSchema,
    type InspectionFormValues,
} from "./inspection.schema"
import {
    INSPECTION_ROUTES,
    DEPARTMENT_ROUTES,
    JOB_CARD_ROUTES,
    TAX_ROUTES,
    InspectionStatus,
    RateType,
} from "@garage/api"
import { RhfVehicleSelectField } from "@/modules/vehicles/rhf-vehicle-select-field"
import { RhfCustomerSelectField } from "@/modules/customers/rhf-customer-select-field"
import { RhfEmployeeSelectField } from "@/modules/employees/rhf-employee-select-field"

// ── Props ──

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

// ── Default values ──

const DEFAULT_VALUES: InspectionFormValues = {
    customer: null,
    vehicle: null,
    department: null,
    inspection_category: null,
    employee: null,
    job_card: null,
    labor_rate: null,
    title: "",
    order_number: "",
    date: "",
    time: "",
    status: "in_progress",
    note: "",
    description: "",
    rate_type: "flat_rate",
    quantity: 1,
    rate: 0,
    working_hours: 0,
    labor_hours: 0,
    tax: null,
    chart_of_account: "",
}

// ── Mapping helpers ──

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

    return {
        customer: toRelation(d.customer_id, d.customer?.first_name ? `${d.customer.first_name} ${d.customer.last_name ?? ""}`.trim() : undefined),
        vehicle: toRelation(d.vehicle_id, d.vehicle?.make ? `${d.vehicle.make} ${d.vehicle.model ?? ""}`.trim() : undefined),
        department: toRelation(d.department_id, d.department?.name),
        inspection_category: toRelation(d.inspection_category_id, d.inspection_category?.name),
        employee: toRelation(d.employee_id, d.employee?.first_name ? `${d.employee.first_name} ${d.employee.last_name ?? ""}`.trim() : undefined),
        job_card: d.job_card_id
            ? { value: String(d.job_card_id), label: d.job_card?.title ?? d.job_card?.order_number ?? String(d.job_card_id) }
            : null,
        labor_rate: d.labor_rate_id
            ? { value: String(d.labor_rate_id), label: d.labor_rate?.title ?? String(d.labor_rate_id) }
            : null,
        title: d.title ?? "",
        order_number: d.order_number ?? "",
        date: d.date ? d.date.split("T")[0] : "",
        time: d.time ?? "",
        status: d.status ?? "in_progress",
        note: d.note ?? "",
        description: d.description ?? "",
        rate_type: d.rate_type ?? "flat_rate",
        quantity: d.quantity != null ? Number(d.quantity) : 1,
        rate: d.rate != null ? Number(d.rate) : 0,
        working_hours: d.working_hours != null ? Number(d.working_hours) : 0,
        labor_hours: d.labor_hours != null ? Number(d.labor_hours) : 0,
        tax: d.tax_id
            ? {
                value: String(d.tax_id),
                label: d.tax?.title
                    ? `${d.tax.title}${d.tax?.rate != null ? ` (${d.tax.rate}%)` : ""}`
                    : `#${d.tax_id}`,
            }
            : null,
        chart_of_account: d.chart_of_account ?? "",
    }
}

function mapFormToPayload(values: InspectionFormValues) {
    return {
        customer_id: toId(values.customer),
        vehicle_id: toId(values.vehicle),
        department_id: toId(values.department),
        inspection_category_id: toId(values.inspection_category),
        employee_id: toId(values.employee),
        job_card_id: values.job_card?.value ?? undefined,
        labor_rate_id: values.labor_rate ? Number(values.labor_rate.value) : undefined,
        title: values.title,
        order_number: values.order_number || undefined,
        date: values.date || undefined,
        time: values.time || undefined,
        status: values.status || undefined,
        note: values.note || undefined,
        description: values.description || undefined,
        rate_type: values.rate_type || undefined,
        quantity: values.quantity ?? undefined,
        rate: values.rate ?? undefined,
        working_hours: values.working_hours ?? undefined,
        labor_hours: values.labor_hours ?? undefined,
        tax_id: values.tax?.value ? Number(values.tax.value) : undefined,
        chart_of_account: values.chart_of_account || undefined,
    }
}

// ── Select options ──

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

const RATE_TYPE_OPTIONS = RateType.map((v) => ({
    value: v,
    label: v === "flat_rate" ? "Flat Rate" : "Hourly",
}))

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

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

// ── Customer-scoped vehicle picker ──
// Watches the `customer` field. When it changes, clears the `vehicle` selection so a stale
// vehicle from a previous customer doesn't get submitted. While no customer is picked, the
// vehicle field is disabled — picking a vehicle without a customer makes no garage sense.

function CustomerScopedVehicleField() {
    const { setValue, control, getValues } = useFormContext<InspectionFormValues>()
    const customer = useWatch({ control, name: "customer" })
    const customerId = customer?.value ?? null
    const lastCustomerIdRef = useRef<string | null>(customerId)

    useEffect(() => {
        if (lastCustomerIdRef.current !== customerId) {
            const currentVehicle = getValues("vehicle")
            if (currentVehicle) {
                setValue("vehicle", null, { shouldDirty: true, shouldValidate: false })
            }
            lastCustomerIdRef.current = customerId
        }
    }, [customerId, setValue, getValues])

    return (
        <RhfVehicleSelectField
            name="vehicle"
            customer_id={customerId}
            disabled={!customerId}
            placeholder={customerId ? "Search this customer's vehicles…" : "Select a customer first"}
        />
    )
}

// ── Component ──

export function InspectionForm({ resourceId, initialData, onSuccess }: InspectionFormProps) {
    const api = useAuthApi()

    const { form, isEditing } = useResourceForm<InspectionFormValues, any>({
        schema: inspectionFormSchema,
        defaultValues: DEFAULT_VALUES,
        resourceId,
        initialData,
        queryKey: [INSPECTION_ROUTES.BY_ID, resourceId],
        mapToFormValues: mapToFormValues,
    })

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

            <FieldGroup>
                <RhfTextField name="title" label="Title" placeholder="e.g. Pre-purchase" required />

                <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                    <RhfCustomerSelectField name="customer" />
                    <CustomerScopedVehicleField />
                </div>

                <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                    <RhfAsyncSelectField
                        name="department"
                        label="Department"
                        placeholder="Select department"
                        queryKey={[DEPARTMENT_ROUTES.INDEX]}
                        listFn={() => api.departments.list()}
                        mapOption={mapLookupOption}
                        createForm={(props) => <DepartmentInlineForm {...props} />}
                        createLabel="Department"
                        {...STORE_OBJECT}
                    />
                    <RhfAsyncSelectField
                        name="inspection_category"
                        label="Inspection Category"
                        placeholder="Select category"
                        queryKey={[INSPECTION_ROUTES.CATEGORIES]}
                        listFn={() => api.inspections.listCategories()}
                        mapOption={(item: any) => ({
                            value: String(item.id),
                            label: item.inspection_name ?? item.name ?? item.title ?? `#${item.id}`,
                        })}
                        createForm={(props) => <InspectionCategoryInlineForm {...props} />}
                        createLabel="Inspection Category"
                        {...STORE_OBJECT}
                    />
                </div>

                <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                    <RhfEmployeeSelectField name="employee" />
                    <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.order_number ?? String(item.id),
                        })}
                        {...STORE_OBJECT}
                    />
                </div>

                <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                    <RhfSelectField
                        name="status"
                        label="Status"
                        placeholder="Select status"
                        options={STATUS_OPTIONS}
                    />
                    <RhfTextField name="order_number" label="Order Number" placeholder="e.g. ORD-001" />
                </div>

                <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                    <RhfDateField name="date" label="Date" />
                    <RhfTimeField name="time" label="Time" withSeconds />
                </div>

                <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                    <RhfSelectField
                        name="rate_type"
                        label="Rate Type"
                        placeholder="Select rate type"
                        options={RATE_TYPE_OPTIONS}
                    />
                    <RhfAsyncSelectField
                        name="labor_rate"
                        label="Labor Rate"
                        placeholder="Select labor rate"
                        queryKey={["labor-rates"]}
                        listFn={() => api.inventory.listLaborRates()}
                        mapOption={(item: any) => ({
                            value: String(item.id),
                            label: item.title ?? String(item.id),
                        })}
                        {...STORE_OBJECT}
                    />
                </div>

                <div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
                    <RhfTextField name="quantity" label="Quantity" type="number" placeholder="1" />
                    <RhfTextField name="rate" label="Rate" type="number" placeholder="0.00" />
                    <RhfAsyncSelectField
                        name="tax"
                        label="Tax"
                        placeholder="Select tax rate"
                        queryKey={[TAX_ROUTES.INDEX]}
                        listFn={() => api.taxes.list()}
                        mapOption={(item: any) => ({
                            value: String(item.id),
                            label: item.title
                                ? `${item.title}${item.rate != null ? ` (${item.rate}%)` : ""}`
                                : `#${item.id}`,
                        })}
                        {...STORE_OBJECT}
                    />
                </div>

                <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                    <RhfTextField name="working_hours" label="Working Hours" type="number" placeholder="0" />
                    <RhfTextField name="labor_hours" label="Labor Hours" type="number" placeholder="0" />
                </div>

                <RhfTextField name="chart_of_account" label="Chart of Account" placeholder="e.g. COA-123" />

                <RhfTextareaField name="note" label="Note" placeholder="Internal notes..." />
                <RhfTextareaField name="description" label="Description" placeholder="Full description..." />

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