"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 { BillStatus, BILL_ROUTES, DEPARTMENT_ROUTES, JOB_CARD_ROUTES, PAYMENT_TERM_ROUTES, VENDOR_ROUTES } from "@garage/api"
import { toast } from "sonner"

import { billFormSchema, type BillFormValues } from "./bill.schema"

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

const DEFAULT_VALUES: BillFormValues = {
    vendor: null,
    job_card: null,
    payment_term: null,
    department: null,
    title: "",
    bill_date: "",
    bill_due_date: "",
    status: "draft",
    notes: "",
}

const STATUS_OPTIONS = BillStatus.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): BillFormValues {
    const d = (data as any)?.data ?? data ?? {}

    return {
        vendor: toRelation(d.vendor_id, d.vendor_name),
        job_card: toRelation(d.job_card_id, d.job_card_number ?? d.job_card_name),
        payment_term: toRelation(d.payment_terms_id, d.payment_terms_name),
        department: toRelation(d.department_id, d.department_name),
        title: d.title || "",
        bill_date: d.bill_date || "",
        bill_due_date: d.bill_due_date || "",
        status: d.status || "draft",
        notes: d.notes || "",
    }
}

function mapFormToPayload(values: BillFormValues) {
    return {
        title: values.title,
        vendor_id: toId(values.vendor),
        job_card_id: toId(values.job_card),
        payment_terms_id: toId(values.payment_term),
        department_id: toId(values.department),
        bill_date: values.bill_date || undefined,
        bill_due_date: values.bill_due_date || undefined,
        status: values.status || undefined,
        notes: values.notes || undefined,
    }
}

export function BillForm({ resourceId, initialData, onSuccess }: BillFormProps) {
    const api = useAuthApi()

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

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

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

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

            <FieldGroup>
                <RhfTextField name="title" label="Title" placeholder="Enter bill title" required />

                <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                    <RhfTextField name="bill_date" label="Bill Date" type="date" />
                    <RhfTextField name="bill_due_date" label="Due Date" type="date" />
                </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>

                <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                    <RhfAsyncSelectField
                        name="job_card"
                        label="Job Card"
                        placeholder="Select job card"
                        queryKey={[JOB_CARD_ROUTES.INDEX]}
                        listFn={() => api.jobCards.list()}
                        mapOption={(item: any) => ({ value: String(item.id), label: item.job_card_number || item.name || `#${item.id}` })}
                        {...STORE_OBJECT}
                    />
                    <RhfAsyncSelectField
                        name="payment_term"
                        label="Payment Term"
                        placeholder="Select payment term"
                        queryKey={[PAYMENT_TERM_ROUTES.INDEX]}
                        listFn={() => api.paymentTerms.list()}
                        mapOption={mapLookupOption}
                        {...STORE_OBJECT}
                    />
                </div>

                <RhfSelectField name="status" label="Status" options={STATUS_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 Bill
                        </>
                    ) : (
                        <>
                            <Plus className="me-2 h-4 w-4" />
                            Create Bill
                        </>
                    )}
                </Button>
            </FieldGroup>
        </Rhform>
    )
}
