"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,
    RhfAsyncSelectField,
    RhfSelectField,
    RhfTextField,
    RhfTextareaField,
} from "@/shared/components/form"
import { useResourceForm } from "@/shared/hooks/use-resource-form"
import { useFormMutation } from "@/shared/hooks/use-form-mutation"
import { toId, toRelation } from "@/shared/lib/utils"
import { useAuthApi } from "@/shared/useApi"
import { BILL_ROUTES, DEPARTMENT_ROUTES, DiscountType, VENDOR_CREDIT_ROUTES, VENDOR_ROUTES, VendorCreditStatus } from "@garage/api"
import { toast } from "sonner"

import { vendorCreditFormSchema, type VendorCreditFormValues } from "./vendor-credit.schema"

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

const DEFAULT_VALUES: VendorCreditFormValues = {
    vendor: null,
    bill: null,
    department: null,
    subject: "",
    vendor_credit_date: "",
    status: "draft",
    discount: "no",
    notes: "",
}

const STATUS_OPTIONS = VendorCreditStatus.map((value) => ({
    value,
    label: value.replaceAll("_", " "),
}))

const DISCOUNT_OPTIONS = DiscountType.map((value) => ({
    value,
    label: value.replaceAll("_", " "),
}))

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

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

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

    return {
        vendor: toRelation(d.vendor_id, d.vendor_name),
        bill: toRelation(d.bill_id, d.bill_number ?? d.bill_name),
        department: toRelation(d.department_id, d.department_name),
        subject: d.subject || "",
        vendor_credit_date: d.vendor_credit_date || "",
        status: d.status || "draft",
        discount: d.discount || "no",
        notes: d.notes || "",
    }
}

function mapFormToPayload(values: VendorCreditFormValues) {
    return {
        subject: values.subject,
        vendor_id: toId(values.vendor),
        bill_id: toId(values.bill),
        department_id: toId(values.department),
        vendor_credit_date: values.vendor_credit_date || undefined,
        status: values.status || undefined,
        discount: values.discount || undefined,
        notes: values.notes || undefined,
    }
}

export function VendorCreditForm({ resourceId, initialData, onSuccess }: VendorCreditFormProps) {
    const api = useAuthApi()

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

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

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

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

            <FieldGroup>
                <RhfTextField name="subject" label="Subject" placeholder="Enter vendor credit subject" required />

                <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                    <RhfTextField name="vendor_credit_date" label="Date" type="date" />
                    <RhfSelectField name="status" label="Status" options={STATUS_OPTIONS} />
                </div>

                <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                    <RhfAsyncSelectField
                        name="vendor"
                        label="Vendor"
                        placeholder="Select vendor"
                        queryKey={[VENDOR_ROUTES.INDEX]}
                        listFn={() => api.vendors.list()}
                        mapOption={mapLookupOption}
                        {...STORE_OBJECT}
                    />
                    <RhfAsyncSelectField
                        name="department"
                        label="Department"
                        placeholder="Select department"
                        queryKey={[DEPARTMENT_ROUTES.INDEX]}
                        listFn={() => api.departments.list()}
                        mapOption={mapLookupOption}
                        {...STORE_OBJECT}
                    />
                </div>

                <RhfAsyncSelectField
                    name="bill"
                    label="Bill"
                    placeholder="Select bill"
                    queryKey={[BILL_ROUTES.INDEX]}
                    listFn={() => api.bills.list()}
                    mapOption={(item: any) => ({ value: String(item.id), label: item.bill_number || item.title || `#${item.id}` })}
                    {...STORE_OBJECT}
                />

                <RhfSelectField name="discount" label="Discount" options={DISCOUNT_OPTIONS} />
                <RhfTextareaField name="notes" label="Notes" rows={3} />

                <Button type="submit" disabled={isPending}>
                    {isPending ? (
                        "Saving..."
                    ) : isEditing ? (
                        <>
                            <Save className="me-2 h-4 w-4" />
                            Update Vendor Credit
                        </>
                    ) : (
                        <>
                            <Plus className="me-2 h-4 w-4" />
                            Create Vendor Credit
                        </>
                    )}
                </Button>
            </FieldGroup>
        </Rhform>
    )
}
