"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 { generalPreferencesFormSchema, type GeneralPreferencesFormValues } 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: GeneralPreferencesFormValues = {
    sell_rates_tax_inclusive: undefined,
    give_discounts: undefined,
    purchase_rates_tax_inclusive: undefined,
    receive_discounts: undefined,
}

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

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

    const { mutate, error, isPending } = useFormMutation(form, {
        mutationFn: (values: GeneralPreferencesFormValues) => {
            const promise = api.configurations.updateGeneralPreferences(values)
            toast.promise(promise, {
                loading: "Saving general preferences...",
                success: "General preferences saved",
                error: "Failed to save general preferences",
            })
            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 general preferences</AlertTitle>
                    {error.message}
                </Alert>
            )}

            <FieldGroup>
                <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                    <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>

                <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                    <RhfSelectField
                        name="purchase_rates_tax_inclusive"
                        label="Purchase Rates Tax"
                        placeholder="Select tax type"
                        options={TAX_INCLUSIVE_OPTIONS}
                    />
                    <RhfSelectField
                        name="receive_discounts"
                        label="Receive Discounts"
                        placeholder="Select discount type"
                        options={DISCOUNT_OPTIONS}
                    />
                </div>

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