"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 } 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 { INSURANCE_TYPE_ROUTES } from "@garage/api"
import { insuranceTypeFormSchema, type InsuranceTypeFormValues } from "./insurance-type.schema"

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

const DEFAULT_VALUES: InsuranceTypeFormValues = {
    title: "",
    description: "",
}

function mapToFormValues(data: unknown): InsuranceTypeFormValues {
    const d = (data as any)?.data ?? data ?? {}
    return {
        title: d.title ?? d.name ?? "",
        description: d.description ?? "",
    }
}

function mapFormToPayload(values: InsuranceTypeFormValues) {
    return {
        title: values.title,
        description: values.description,
    }
}

export function InsuranceTypeForm({ resourceId, initialData, onSuccess }: InsuranceTypeFormProps) {
    const api = useAuthApi()

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

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

            toast.promise(promise, {
                loading: isEditing ? "Updating insurance type..." : "Creating insurance type...",
                success: isEditing ? "Insurance type updated successfully" : "Insurance type created successfully",
                error: isEditing ? "Failed to update insurance type" : "Failed to create insurance type",
            })

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

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

                <RhfTextField
                    name="description"
                    label="Description"
                    placeholder="Short description"
                    required
                />

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