"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,
    RhfSelectField,
    RhfTextareaField,
} 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, INSURANCE_TYPE_ROUTES, DiscountType } 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"
import { RhfEmployeeSelectField } from "@/modules/employees/rhf-employee-select-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,
    insurance_type: null,
    insurer: null,
    service_writer: null,
    estimate_number: "",
    date: "",
    has_insurance: false,
    enable_digital_authorisation: false,
    footer: "",
    discount: "no",
    discount_amount: undefined,
    remarks: [],
    labels: [],
}

// ── Mapping helpers ──

function customerLabel(c: any): string | undefined {
    if (!c) return undefined
    const name = [c.first_name, c.last_name].filter(Boolean).join(" ").trim()
    return c.company_name || name || undefined
}

function vehicleLabel(v: any): string | undefined {
    if (!v) return undefined
    const core = [v.make, v.model, v.sub_model].filter(Boolean).join(" ")
    const suffix = [v.year, v.license_plate].filter(Boolean).join(" - ")
    if (core && suffix) return `${core} (${suffix})`
    return core || suffix || undefined
}

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

    return {
        title: d.title || "",
        customer: toRelation(
            d.customer_id ?? d.customer?.id,
            d.customer_name ?? customerLabel(d.customer),
        ),
        vehicle: toRelation(
            d.vehicle_id ?? d.vehicle?.id,
            d.vehicle_name ?? vehicleLabel(d.vehicle),
        ),
        department: toRelation(
            d.department_id ?? d.department?.id,
            d.department_name ?? d.department?.name ?? d.department?.title,
        ),
        insurance_type: toRelation(
            d.insurance_type_id ?? d.insurance_type?.id,
            d.insurance_type_title ?? d.insurance_type_name ?? d.insurance_type?.title ?? d.insurance_type?.name,
        ),
        insurer: toRelation(
            d.insurer_id ?? d.insurer?.id,
            d.insurer_name ?? customerLabel(d.insurer),
        ),
        service_writer: toRelation(
            d.service_writer_id ?? d.service_writer?.id,
            d.service_writer_name ?? customerLabel(d.service_writer),
        ),
        estimate_number: d.estimate_number || "",
        date: d.date ? d.date.split("T")[0] : "",
        has_insurance: d.has_insurance ?? false,
        enable_digital_authorisation: d.enable_digital_authorisation ?? false,
        footer: d.footer ?? "",
        discount: d.discount ?? d.discount_type ?? "no",
        discount_amount: d.discount_amount != null ? Number(d.discount_amount) : undefined,
        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),
        insurance_type_id: values.insurance_type ? String(toId(values.insurance_type)) : null,
        insurer_id: toId(values.insurer),
        service_writer_id: toId(values.service_writer),
        estimate_number: values.estimate_number || undefined,
        date: values.date || undefined,
        has_insurance: values.has_insurance,
        enable_digital_authorisation: values.enable_digital_authorisation,
        footer: values.footer || undefined,
        discount: values.discount || undefined,
        discount_amount: values.discount_amount,
        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 }

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

// ── Component ──

export function EstimateForm({ resourceId, initialData, onSuccess }: EstimateFormProps) {
    const api = useAuthApi()

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

    const { mutate, error, isPending } = useFormMutation(form, {
        mutationFn: (values: EstimateFormValues) => {
            const payload = mapFormToPayload(values)
            const promise = (isEditing && resourceId
                ? api.estimates.update(resourceId, payload as any)
                : api.estimates.create(payload as any)) 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: () => {
            if (!isEditing) 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" required />
                    <RhfVehicleSelectField name="vehicle" required />
                </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" required />
                </div>

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

                <div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
                    <RhfAsyncSelectField
                        name="insurance_type"
                        label="Insurance Type"
                        placeholder="Select insurance type"
                        queryKey={[INSURANCE_TYPE_ROUTES.INDEX]}
                        listFn={() => api.insuranceTypes.list()}
                        mapOption={mapLookupOption}
                        {...STORE_OBJECT}
                    />
                    <RhfCustomerSelectField
                        name="insurer"
                        label="Insurer"
                        placeholder="Search insurer..."
                        customerType="Insurer"
                    />
                    <RhfEmployeeSelectField name="service_writer" label="Service Writer" />
                </div>

                <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                    <RhfSelectField name="discount" label="Discount" options={DISCOUNT_OPTIONS} />
                    <RhfTextField name="discount_amount" label="Discount Amount" type="number" placeholder="0.00" />
                </div>

                <RhfCheckboxField name="enable_digital_authorisation" label="Enable Digital Authorisation" />

                <RhfTextareaField name="footer" label="Footer" placeholder="Footer notes for this estimate" />

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