"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,
    RhfCheckboxField,
    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 { makeAndModelFormSchema, type MakeAndModelFormValues } from "./make-and-model.schema"
import { MAKE_AND_MODEL_ROUTES } from "@garage/api"

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

const DEFAULT_VALUES: MakeAndModelFormValues = {
    make: "",
    model: "",
    year: "",
    sub_model: "",
    engine_size: "",
    drivetrain: "",
    shop_type: null,
    body_type: null,
    fuel_type: null,
    transmission: null,
    is_active: true,
}

function mapToFormValues(data: unknown): MakeAndModelFormValues {
    const d = (data as any)?.data ?? data ?? {}
    return {
        make: d.make ?? "",
        model: d.model ?? "",
        year: d.year ?? "",
        sub_model: d.sub_model ?? "",
        engine_size: d.engine_size ?? "",
        drivetrain: d.drivetrain ?? "",
        shop_type: toRelation(d.shop_type_id, d.shop_type_title ?? d.shop_type_name),
        body_type: toRelation(d.body_type_id, d.body_type_title ?? d.body_type_name),
        fuel_type: toRelation(d.fuel_id, d.fuel_title ?? d.fuel_name),
        transmission: toRelation(d.transmission_id, d.transmission_title ?? d.transmission_name),
        is_active: d.is_active ?? true,
    }
}

function mapFormToPayload(values: MakeAndModelFormValues) {
    return {
        make: values.make,
        model: values.model,
        year: values.year || undefined,
        sub_model: values.sub_model || undefined,
        engine_size: values.engine_size || undefined,
        drivetrain: values.drivetrain || undefined,
        shop_type_id: toId(values.shop_type),
        body_type_id: toId(values.body_type),
        fuel_id: toId(values.fuel_type),
        transmission_id: toId(values.transmission),
        is_active: values.is_active,
    }
}

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

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

export function MakeAndModelForm({ resourceId, initialData, onSuccess }: MakeAndModelFormProps) {
    const api = useAuthApi()

    const { form, isEditing } = useResourceForm<MakeAndModelFormValues, any>({
        schema: makeAndModelFormSchema,
        defaultValues: DEFAULT_VALUES,
        resourceId,
        initialData,
        initialize: (id) => api.makeAndModels.show(id),
        queryKey: [MAKE_AND_MODEL_ROUTES.BY_ID, resourceId],
        mapToFormValues,
    })

    const { mutate, error, isPending } = useFormMutation(form, {
        mutationFn: (values: MakeAndModelFormValues) => {
            const payload = mapFormToPayload(values)
            const promise = isEditing && resourceId
                ? api.makeAndModels.update(resourceId, payload)
                : api.makeAndModels.create(payload)

            toast.promise(promise, {
                loading: isEditing ? "Updating make & model..." : "Creating make & model...",
                success: isEditing ? "Make & model updated successfully" : "Make & model created successfully",
                error: isEditing ? "Failed to update make & model" : "Failed to create make & model",
            })

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

            <FieldGroup>
                <RhfTextField
                    name="make"
                    label="Make"
                    placeholder="e.g. Toyota"
                    required
                />

                <RhfTextField
                    name="model"
                    label="Model"
                    placeholder="e.g. Camry"
                    required
                />

                <RhfTextField
                    name="year"
                    label="Year"
                    placeholder="e.g. 2022"
                />

                <RhfTextField
                    name="sub_model"
                    label="Sub Model"
                    placeholder="e.g. LE"
                />

                <RhfAsyncSelectField
                    name="shop_type"
                    label="Shop Type"
                    placeholder="Select shop type..."
                    queryKey={["shop-types-list"]}
                    listFn={() => api.shopTypes.list()}
                    mapOption={mapLookupOption}
                    {...STORE_OBJECT}
                />

                <RhfAsyncSelectField
                    name="body_type"
                    label="Body Type"
                    placeholder="Select body type..."
                    queryKey={["body-types-list"]}
                    listFn={() => api.vehicleAttributes.listBodyTypes()}
                    mapOption={mapLookupOption}
                    {...STORE_OBJECT}
                />

                <RhfAsyncSelectField
                    name="fuel_type"
                    label="Fuel Type"
                    placeholder="Select fuel type..."
                    queryKey={["fuel-types-list"]}
                    listFn={() => api.vehicleAttributes.listFuelTypes()}
                    mapOption={mapLookupOption}
                    {...STORE_OBJECT}
                />

                <RhfAsyncSelectField
                    name="transmission"
                    label="Transmission"
                    placeholder="Select transmission..."
                    queryKey={["transmissions-list"]}
                    listFn={() => api.vehicleAttributes.listTransmissions()}
                    mapOption={mapLookupOption}
                    {...STORE_OBJECT}
                />

                <RhfTextField
                    name="engine_size"
                    label="Engine Size"
                    placeholder="e.g. 2.5L"
                />

                <RhfTextField
                    name="drivetrain"
                    label="Drivetrain"
                    placeholder="e.g. FWD"
                />

                <RhfCheckboxField
                    name="is_active"
                    label="Active"
                />

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