"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,
    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 { toId, toRelation } from "@/shared/lib/utils"

import {
    vendorFormSchema,
    type VendorFormValues,
} from "./vendor.schema"
import { VENDOR_ROUTES } from "@garage/api"

// ── Props ──

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

// ── Default values ──

const DEFAULT_VALUES: VendorFormValues = {
    salutation: "Mr.",
    first_name: "",
    last_name: "",
    company_name: "",
    email: "",
    phone: "",
    alternate_phone: "",
    address_line_1: "",
    address_line_2: "",
    city: "",
    zip_code: "",
    country: null,
    state: null,
} as any

// ── Mapping helpers ──

const mapLookupOption = (item: any) => ({ value: String(item.id), label: item.name })
const STORE_OBJECT = { getOptionValue: (o: any) => o, getOptionLabel: (o: any) => o.label }

function mapToFormValues(data: unknown): VendorFormValues {
    const d = (data as any)?.data ?? data ?? {}
    const address = Array.isArray(d.addresses) ? d.addresses[0] ?? {} : {}

    return {
        first_name: d.first_name || "",
        last_name: d.last_name || "",
        company_name: d.company_name || "",
        email: d.email || "",
        phone: d.phone || "",
        alternate_phone: d.alternate_phone || "",
        address_line_1: address.address_line_1 || "",
        address_line_2: address.address_line_2 || "",
        city: address.city || "",
        zip_code: address.zip_code || "",
        country: toRelation(address.country_id, address.country?.name),
        state: toRelation(address.state_id, address.state?.name),
    } as VendorFormValues
}

function mapFormToPayload(values: VendorFormValues) {
    return {
        first_name: values.first_name,
        last_name: values.last_name || undefined,
        company_name: values.company_name || undefined,
        email: values.email || undefined,
        phone: values.phone || undefined,
        alternate_phone: values.alternate_phone || undefined,
        address_line_1: values.address_line_1 || undefined,
        address_line_2: values.address_line_2 || undefined,
        city: values.city || undefined,
        zip_code: values.zip_code || undefined,
        country_id: toId(values.country),
        state_id: toId(values.state),
    }
}

// ── Component ──

export function VendorForm({ resourceId, initialData, onSuccess }: VendorFormProps) {
    const api = useAuthApi()

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

    const { mutate, error, isPending } = useFormMutation(form, {
        mutationFn: (values: VendorFormValues) => {
            const payload = mapFormToPayload(values)
            const promise = isEditing && resourceId
                ? api.vendors.update(resourceId, payload)
                : api.vendors.create(payload)
            toast.promise(promise, {
                loading: isEditing ? "Updating vendor..." : "Creating vendor...",
                success: isEditing ? "Vendor updated successfully" : "Vendor created successfully",
                error: isEditing ? "Failed to update vendor" : "Failed to create vendor",
            })
            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 vendor" : "Failed to create vendor"}
                    </AlertTitle>
                    {error.message}
                </Alert>
            )}

            <FieldGroup>
                <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                    <RhfTextField name="first_name" label="First Name" placeholder="John" required />
                    <RhfTextField name="last_name" label="Last Name" placeholder="Doe" required />
                </div>

                <RhfTextField name="company_name" label="Company Name" placeholder="Acme Supplies" required />
                <RhfTextField name="email" label="Email" placeholder="vendor@example.com" type="email" required />

                <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                    <RhfTextField name="phone" label="Phone" placeholder="+971501234567" type="tel" />
                    <RhfTextField name="alternate_phone" label="Alternate Phone" placeholder="+971509876543" type="tel" />
                </div>

                {/* ── Address ── */}
                <div className="border-t pt-4">
                    <h3 className="mb-3 text-sm font-semibold">Address</h3>
                    <RhfTextField name="address_line_1" label="Address Line 1" placeholder="Street 10" />
                    <div className="mt-4">
                        <RhfTextField name="address_line_2" label="Address Line 2" placeholder="Near Central Plaza" />
                    </div>

                    <div className="mt-4 grid grid-cols-1 gap-4 sm:grid-cols-2">
                        <RhfAsyncSelectField
                            name="country"
                            label="Country"
                            placeholder="Select country"
                            queryKey={["countries"]}
                            listFn={() => api.geo.countries()}
                            mapOption={mapLookupOption}
                            {...STORE_OBJECT}
                        />
                        <RhfAsyncSelectField
                            name="state"
                            label="State"
                            placeholder="Select state"
                            queryKey={["states"]}
                            listFn={() => api.geo.states()}
                            mapOption={mapLookupOption}
                            {...STORE_OBJECT}
                        />
                    </div>

                    <div className="mt-4 grid grid-cols-1 gap-4 sm:grid-cols-2">
                        <RhfTextField name="city" label="City" placeholder="Dubai" />
                        <RhfTextField name="zip_code" label="Zip Code" placeholder="00000" />
                    </div>
                </div>

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