"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, RhfDateField, RhfTextField, RhfTimeField, 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 { mileageFormSchema, type MileageFormValues } from "./mileage.schema"

// ── Props ──

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

// ── Default values ──

const DEFAULT_VALUES: MileageFormValues = {
    miles: 0,
    fuel_level: undefined,
    date: "",
    time: "",
    note: "",
}

// ── Mapping helpers ──

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

    const date = d.date ? String(d.date).split("T")[0] : ""
    const time = d.time
        ? String(d.time).includes("T")
            ? String(d.time).split("T")[1]?.slice(0, 8) ?? ""
            : String(d.time).slice(0, 8)
        : ""

    return {
        miles: d.miles ?? d.mileage ?? 0,
        fuel_level: d.fuel_level ?? undefined,
        date,
        time,
        note: d.note || "",
    }
}

// ── Component ──

export function MileageForm({ vehicleId, resourceId, initialData, onSuccess }: MileageFormProps) {
    const api = useAuthApi()

    const { form, isEditing } = useResourceForm<MileageFormValues, any>({
        schema: mileageFormSchema,
        defaultValues: DEFAULT_VALUES,
        resourceId,
        initialData,
        mapToFormValues,
    })

    const { mutate, error, isPending } = useFormMutation(form, {
        mutationFn: (values: MileageFormValues) => {
            const payload = {
                miles: values.miles,
                fuel_level: values.fuel_level,
                date: values.date,
                time: values.time,
                note: values.note || undefined,
            }
            const promise = isEditing && resourceId
                ? api.vehicleDocuments.updateMileage(resourceId, payload as any)
                : api.vehicleDocuments.createMileage({ vehicle_id: Number(vehicleId), ...payload } as any)
            toast.promise(promise, {
                loading: isEditing ? "Updating mileage..." : "Adding mileage...",
                success: isEditing ? "Mileage updated successfully" : "Mileage added successfully",
                error: isEditing ? "Failed to update mileage" : "Failed to add mileage",
            })
            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 mileage" : "Failed to add mileage"}
                    </AlertTitle>
                    {error.message}
                </Alert>
            )}

            <FieldGroup>
                <RhfTextField
                    name="miles"
                    label="Miles"
                    placeholder="e.g. 50000"
                    type="number"
                    required
                />

                <RhfTextField
                    name="fuel_level"
                    label="Fuel Level (%)"
                    placeholder="e.g. 80"
                    type="number"
                />

                <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                    <RhfDateField
                        name="date"
                        label="Date"
                        required
                    />
                    <RhfTimeField
                        name="time"
                        label="Time"
                         required
                    />
                </div>

                <RhfTextareaField
                    name="note"
                    label="Note"
                    placeholder="Optional note"
                />

                <Button type="submit" disabled={isPending} className="w-full">
                    {isPending ? null : isEditing ? <Save /> : <Plus />}
                    {isPending ? "Saving..." : isEditing ? "Update Mileage" : "Add Mileage"}
                </Button>
            </FieldGroup>
        </Rhform>
    )
}
