"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,
    RhfSelectField,
    RhfTextareaField,
    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 {
    creditNoteFormSchema,
    type CreditNoteFormValues,
} from "./credit-note.schema"
import { CREDIT_NOTE_ROUTES, DEPARTMENT_ROUTES, CreditNoteStatus } from "@garage/api"
import { RhfCustomerSelectField } from "@/modules/customers/rhf-customer-select-field"

// ── Shared mapOption for async selects ──

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

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

// ── Constants ──

const STATUS_OPTIONS = CreditNoteStatus.map((v) => ({
    value: v,
    label: v.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase()),
}))

// ── Props ──

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

// ── Default values ──

const DEFAULT_VALUES: CreditNoteFormValues = {
    subject: "",
    customer: null,
    department: null,
    date: "",
    status: "draft",
    notes: "",
}

// ── Mapping helpers ──

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

    return {
        subject: d.subject || "",
        customer: toRelation(d.customer_id, d.customer_name),
        department: toRelation(d.department_id, d.department_name),
        date: d.date || "",
        status: d.status || "draft",
        notes: d.notes || "",
    }
}

function mapFormToPayload(values: CreditNoteFormValues) {
    return {
        subject: values.subject,
        customer_id: toId(values.customer),
        department_id: toId(values.department),
        date: values.date || undefined,
        status: values.status,
        notes: values.notes || undefined,
    }
}

// ── Component ──

export function CreditNoteForm({ resourceId, initialData, onSuccess }: CreditNoteFormProps) {
    const api = useAuthApi()

    const { form, isEditing } = useResourceForm<CreditNoteFormValues>({
        schema: creditNoteFormSchema,
        defaultValues: DEFAULT_VALUES,
        resourceId: resourceId ?? null,
        initialData,
        queryKey: [CREDIT_NOTE_ROUTES.BY_ID, resourceId],
        initialize: (id) => api.creditNotes.show(id),
        mapToFormValues,
    })

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

            <FieldGroup>
                <RhfTextField name="subject" label="Subject" placeholder="Credit note subject" required />

                <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                    <RhfCustomerSelectField name="customer" label="Customer" />

                    <RhfAsyncSelectField
                        name="department"
                        label="Department"
                        placeholder="Select department"
                        queryKey={[DEPARTMENT_ROUTES.INDEX]}
                        listFn={() => api.departments.list()}
                        mapOption={mapLookupOption}
                        {...STORE_OBJECT}
                    />
                </div>

                <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                    <RhfTextField name="date" label="Date" type="date" />

                    <RhfSelectField
                        name="status"
                        label="Status"
                        options={STATUS_OPTIONS}
                    />
                </div>

                <RhfTextareaField name="notes" label="Notes" placeholder="Additional notes..." rows={3} />

                <Button type="submit" variant="default" disabled={isPending}>
                    {isEditing ? (
                        <>
                            <Save className="me-2 size-4" />
                            {isPending ? "Saving..." : "Save Changes"}
                        </>
                    ) : (
                        <>
                            <Plus className="me-2 size-4" />
                            {isPending ? "Creating..." : "Create Credit Note"}
                        </>
                    )}
                </Button>
            </FieldGroup>
        </Rhform>
    )
}
