"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,
    RhfCheckboxField,
    RhfImageField,
} from "@/shared/components/form"
import { ShopTypeInlineForm } from "./inline-forms/shop-type-inline-form"
import { BodyTypeInlineForm } from "./inline-forms/body-type-inline-form"
import { FuelTypeInlineForm } from "./inline-forms/fuel-type-inline-form"
import { TransmissionInlineForm } from "./inline-forms/transmission-inline-form"
import { ColorInlineForm } from "./inline-forms/color-inline-form"
import { RhfVehicleIdentityField } from "./rhf-vehicle-identity-field"
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 { formatUppercase } from "@/shared/utils/formatters"
import { VEHICLE_ROUTES, INSURANCE_TYPE_ROUTES } from "@garage/api"

import { vehicleFormSchema, type VehicleFormValues } from "./vehicle.schema"
import { CustomerForm } from "../customers/customer-form"
import { getFullName } from "@/shared/utils/getFullName"
 
// ── Props ──

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

// ── Default values ──

const DEFAULT_VALUES: VehicleFormValues = {
    shop_type_id: null,
    vehicle_body_type_id: null,
    vehicle_fuel_type_id: null,
    vehicle_transmission_id: null,
    vehicle_color_id: null,
    customer_id: null,
    make: "",
    model: "",
    year: "",
    sub_model: "",
    license_plate: "",
    vin_number: "",
    engine_size: "",
    drivetrain: "",
    mileage: "",
    note: "",
    has_insurance: false,
    insurance_type: null,
    image: null,
}

// ── Mapping helpers ──

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 }

const toFormString = (value: unknown): string =>
    value == null ? "" : String(value)

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

    return {
        shop_type_id: toRelation(d.shop_type_id, d.shop_type?.title),
        vehicle_body_type_id: toRelation(d.vehicle_body_type_id, d.vehicle_body_type?.title),
        vehicle_fuel_type_id: toRelation(d.vehicle_fuel_type_id, d.vehicle_fuel_type?.title),
        vehicle_transmission_id: toRelation(d.vehicle_transmission_id, d.vehicle_transmission?.title),
        vehicle_color_id: toRelation(d.vehicle_color_id, d.vehicle_color?.title),
        customer_id: toRelation(d.customer_id, d.customer?.name),
        make: toFormString(d.make),
        model: toFormString(d.model),
        year: toFormString(d.year),
        sub_model: toFormString(d.sub_model),
        license_plate: toFormString(d.license_plate),
        vin_number: toFormString(d.vin_number),
        engine_size: toFormString(d.engine_size),
        drivetrain: toFormString(d.drivetrain),
        mileage: toFormString(d.mileage),
        note: toFormString(d.note),
        has_insurance: Boolean(d.has_insurance),
        insurance_type: toRelation(d.insurance_type_id, d.insurance_type?.title),
        image: null,
    }
}

function mapToPayload(values: VehicleFormValues) {
    return {
        shop_type_id: toId(values.shop_type_id),
        vehicle_body_type_id: toId(values.vehicle_body_type_id),
        vehicle_fuel_type_id: toId(values.vehicle_fuel_type_id),
        vehicle_transmission_id: toId(values.vehicle_transmission_id),
        vehicle_color_id: toId(values.vehicle_color_id),

        customer_id: toId(values.customer_id),
        make: values.make,
        model: values.model,
        year: values.year,
        sub_model: values.sub_model || undefined,
        license_plate: values.license_plate || undefined,
        vin_number: values.vin_number || undefined,
        engine_size: values.engine_size || undefined,
        drivetrain: values.drivetrain || undefined,
        mileage: values.mileage || undefined,
        note: values.note || undefined,
        has_insurance: values.has_insurance ?? false,
        insurance_type_id: values.has_insurance ? toId(values.insurance_type) : undefined,
        image: values.image instanceof File ? values.image : undefined,
    }
}

// ── Component ──

export function VehicleForm({ resourceId, initialData, onSuccess }: VehicleFormProps) {
    const api = useAuthApi()

    const { form, isEditing, data: resolvedData } = useResourceForm<VehicleFormValues, any>({
        schema: vehicleFormSchema,
        defaultValues: DEFAULT_VALUES,
        resourceId,
        initialData,
        initialize: (id) => api.vehicles.getById(id),
        queryKey: [VEHICLE_ROUTES.BY_ID, resourceId],
        mapToFormValues,
    })

    const existingImageUrl: string | null =
        (resolvedData as any)?.data?.image_url ?? (resolvedData as any)?.image_url ?? null

    const hasInsurance = form.watch("has_insurance")

    const { mutate, error, isPending } = useFormMutation(form, {
        mutationFn: (values: VehicleFormValues) => {
            const payload = mapToPayload(values)
            const promise = isEditing && resourceId
                ? api.vehicles.update(resourceId, payload as any)
                : api.vehicles.create(payload as any)
            toast.promise(promise, {
                loading: isEditing ? "Updating vehicle..." : "Creating vehicle...",
                success: isEditing ? "Vehicle updated successfully" : "Vehicle created successfully",
                error: isEditing ? "Failed to update vehicle" : "Failed to create vehicle",
            })
            return promise
        },
        onSuccess: (data) => {
            form.reset()
            onSuccess?.(data)
        },
    })

    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 vehicle" : "Failed to create vehicle"}
                    </AlertTitle>
                    {error.message}
                </Alert>
            )}

            <FieldGroup>
                {/* Vehicle identity — cascading make/model/year/sub_model autocomplete */}
                <RhfVehicleIdentityField />

                {/* Associations */}
                <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                    <RhfAsyncSelectField
                        required
                        name="shop_type_id"
                        label="Shop Type"
                        placeholder="Select shop type"
                        queryKey={["shop-types"]}
                        listFn={() => api.shopTypes.list()}
                        mapOption={mapLookupOption}
                        createForm={(props) => <ShopTypeInlineForm {...props} />}
                        createLabel="Shop Type"
                        {...STORE_OBJECT}
                    />
                    <RhfAsyncSelectField
                        required
                        name="vehicle_body_type_id"
                        label="Body Type"
                        placeholder="Select body type"
                        queryKey={["vehicle-body-types"]}
                        listFn={() => api.vehicleAttributes.listBodyTypes()}
                        mapOption={mapLookupOption}
                        createForm={(props) => <BodyTypeInlineForm {...props} />}
                        createLabel="Body Type"
                        {...STORE_OBJECT}
                    />
                </div>

                <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                    <RhfAsyncSelectField
                        name="vehicle_fuel_type_id"
                        label="Fuel Type"
                        placeholder="Select fuel type"
                        queryKey={["vehicle-fuel-types"]}
                        listFn={() => api.vehicleAttributes.listFuelTypes()}
                        mapOption={mapLookupOption}
                        createForm={(props) => <FuelTypeInlineForm {...props} />}
                        createLabel="Fuel Type"
                        {...STORE_OBJECT}
                    />
                    <RhfAsyncSelectField
                        name="vehicle_transmission_id"
                        label="Transmission"
                        placeholder="Select transmission"
                        queryKey={["vehicle-transmissions"]}
                        listFn={() => api.vehicleAttributes.listTransmissions()}
                        mapOption={mapLookupOption}
                        createForm={(props) => <TransmissionInlineForm {...props} />}
                        createLabel="Transmission"
                        {...STORE_OBJECT}
                    />
                </div>

                <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                    <RhfAsyncSelectField
                        name="vehicle_color_id"
                        label="Color"
                        placeholder="Select color"
                        queryKey={["vehicle-colors"]}
                        listFn={() => api.vehicleAttributes.listColors()}
                        mapOption={mapLookupOption}
                        createForm={(props) => <ColorInlineForm {...props} />}
                        createLabel="Color"
                        {...STORE_OBJECT}
                    />
                    <RhfTextField name="vin_number" label="VIN Number" placeholder="e.g. 1HGBH41JXMN109186" />
                </div>
                <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                    <RhfAsyncSelectField
                        name="customer_id"
                        label="Customer"
                        placeholder="Select customer"
                        queryKey={["customers"]}
                        listFn={() => api.customers.list()}
                        mapOption={(op:any)=> ({ value: String(op.id), label: getFullName(op) })}
                        createForm={(props) => <CustomerForm {...props} />}
                        createLabel="Customer"
                        
                        {...STORE_OBJECT}
                    />
                 </div>

                {/* Insurance */}
                <div className="border-t pt-4">
                    <RhfCheckboxField name="has_insurance" label="Has Insurance?" />
                    {hasInsurance && (
                        <div className="mt-4">
                            <RhfAsyncSelectField
                                name="insurance_type"
                                label="Insurance Type"
                                placeholder="Select insurance type (e.g. Comprehensive)"
                                queryKey={[INSURANCE_TYPE_ROUTES.INDEX]}
                                listFn={() => api.insuranceTypes.list()}
                                mapOption={mapLookupOption}
                                {...STORE_OBJECT}
                            />
                        </div>
                    )}
                </div>

                {/* License & identifiers */}
                <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                    <RhfTextField
                        required
                        name="license_plate"
                        label="License Plate"
                        placeholder="e.g. ABC-123"
                        formatter={formatUppercase}
                    />
                    <RhfTextField name="mileage" label="Mileage" placeholder="e.g. 10000" />
                </div>

                <RhfImageField
                    name="image"
                    label="Image"
                    initialPreviewUrl={existingImageUrl}
                />

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

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