"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 {
    Rhform,
    RhfTextField,
    RhfCheckboxField,
    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 {
    estimateFormSchema,
    type EstimateFormValues,
} from "./estimate.schema"
import { ESTIMATE_ROUTES, DEPARTMENT_ROUTES } from "@garage/api"
import { RhfCustomerSelectField } from "@/modules/customers/rhf-customer-select-field"
import { RhfVehicleSelectField } from "@/modules/vehicles/rhf-vehicle-select-field"
import { RhfLabelPickerField, type LabelItem } from "@/modules/labels/rhf-label-picker-field"
import { RhfCustomerRemarksField } from "./rhf-customer-remarks-field"

// ── Props ──

export type EstimateFormProps = {
    resourceId?: string | null
    initialData?: Partial<EstimateFormValues>
    onSuccess?: () => void
    defaultVehicleId?: string | null
}

// ── Default values ──

const DEFAULT_VALUES: EstimateFormValues = {
    title: "",
    customer: null,
    vehicle: null,
    department: null,
    estimate_number: "",
    date: "",
    has_insurance: false,
    remarks: [],
    labels: [],
}

// ── Mapping helpers ──

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

    return {
        title: d.title || "",
        customer: toRelation(d.customer_id, d.customer_name),
        vehicle: toRelation(d.vehicle_id, d.vehicle_name),
        department: toRelation(d.department_id, d.department_name),
        estimate_number: d.estimate_number || "",
        date: d.date ? d.date.split("T")[0] : "",
        has_insurance: d.has_insurance ?? false,
        remarks: Array.isArray(d.remarks)
            ? d.remarks.map((r: any) => (typeof r === "string" ? r : (r?.remark ?? ""))).filter(Boolean)
            : [],
        labels: (d.labels ?? []).map((l: any): LabelItem => ({
            id: l.id,
            title: l.title ?? l.name ?? "",
            color_code: l.color_code ?? "",
        })),
    }
}

function mapFormToPayload(values: EstimateFormValues) {
    return {
        title: values.title,
        customer_id: toId(values.customer),
        vehicle_id: toId(values.vehicle),
        department_id: toId(values.department),
        estimate_number: values.estimate_number || undefined,
        date: values.date || undefined,
        has_insurance: values.has_insurance,
        remarks: values.remarks?.filter(Boolean) ?? [],
        label_ids: values.labels?.map((l) => l.id) ?? [],
    }
}

// ── 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 EstimateForm({ resourceId, initialData, onSuccess }: EstimateFormProps) {
    const api = useAuthApi()

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

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

            <div className="space-y-4">
                <RhfLabelPickerField name="labels" label="Labels" />

                <RhfTextField name="title" label="Title" placeholder="Estimate title" required />

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

                <div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
                    <RhfAsyncSelectField
                        name="department"
                        label="Department"
                        placeholder="Select department"
                        queryKey={[DEPARTMENT_ROUTES.INDEX]}
                        listFn={() => api.departments.list()}
                        mapOption={mapLookupOption}
                        {...STORE_OBJECT}
                    />
                    <RhfDateField name="date" label="Date" />
                    <RhfAutoGenerateField autoFetch name="estimate_number" label="Estimate#" placeholder="EST-001" table="estimates" />
                </div>

                <RhfCheckboxField name="has_insurance" label="Has Insurance" />

                <RhfCustomerRemarksField name="remarks" />

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