"use client"

import { AlertTriangle, Save } from "lucide-react"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { toast } from "sonner"

import { Button } from "@/shared/components/ui/button"
import { Alert, AlertTitle } from "@/shared/components/ui/alert"
import { FieldGroup } from "@/shared/components/ui/field"
import { Rhform, RhfSelectField } from "@/shared/components/form"
import { useAuthApi } from "@/shared/useApi"
import { useFormMutation } from "@/shared/hooks/use-form-mutation"

import { TaxInclusive, DiscountType } from "@garage/api"
import { salesConfigFormSchema, type SalesConfigFormValues } from "./configurations.schema"

const TAX_INCLUSIVE_OPTIONS = TaxInclusive.map((v) => ({ value: v, label: v }))

const DISCOUNT_OPTIONS = DiscountType.map((v) => ({
    value: v,
    label: v === "no" ? "No Discount" : v === "line_item_level" ? "Line Item Level" : "Transaction Level",
}))

const DEFAULT_VALUES: SalesConfigFormValues = {
    sell_rates_tax_inclusive: undefined,
    give_discounts: undefined,
}

export function SalesConfigForm() {
    const api = useAuthApi()

    const form = useForm<SalesConfigFormValues>({
        resolver: zodResolver(salesConfigFormSchema) as any,
        defaultValues: DEFAULT_VALUES,
    })

    const { mutate, error, isPending } = useFormMutation(form, {
        mutationFn: (values: SalesConfigFormValues) => {
            const promise = api.configurations.updateSalesTaxDiscount(values)
            toast.promise(promise, {
                loading: "Saving sales configuration...",
                success: "Sales configuration saved",
                error: "Failed to save sales configuration",
            })
            return promise
        },
    })

    return (
        <Rhform form={form} onSubmit={(values) => mutate(values)}>
            {error && (
                <Alert variant="destructive" className="mb-4">
                    <AlertTriangle className="me-2 h-4 w-4" />
                    <AlertTitle>Failed to save sales configuration</AlertTitle>
                    {error.message}
                </Alert>
            )}

            <FieldGroup>
                <RhfSelectField
                    name="sell_rates_tax_inclusive"
                    label="Sell Rates Tax"
                    placeholder="Select tax type"
                    options={TAX_INCLUSIVE_OPTIONS}
                />
                <RhfSelectField
                    name="give_discounts"
                    label="Give Discounts"
                    placeholder="Select discount type"
                    options={DISCOUNT_OPTIONS}
                />

                <div className="flex justify-end">
                    <Button type="submit" disabled={isPending}>
                        <Save />
                        {isPending ? "Saving..." : "Save"}
                    </Button>
                </div>
            </FieldGroup>
        </Rhform>
    )
}
