"use client";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { toastError, toastSuccess } from "@/services/custom-toast";
import { useMutation } from "@tanstack/react-query";
import { Loader2 } from "lucide-react";
import { useTranslations } from "next-intl";

import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { z } from "zod";

import postData from "@/api/post-data";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { useState } from "react";
export default function AuctionDialog({ auction }) {
  const [showModal, setShowModal] = useState(false);
  const mutation = useMutation({
    mutationFn: (values) =>
      postData({ endPoint: "/auctions/send/bidding", body: values }),
    onSuccess: (res) => {
      if (res.status === "error" || res.error) {
        return toastError(res.message);
      } else {
        setShowModal(false);
        return toastSuccess(res.message);
      }
    },
  });

  const s = useTranslations();

  const miniumAmountToBidding = auction?.max_bidding
    ? parseInt(auction?.max_bidding) + parseInt(auction?.lowest_bidding)
    : parseInt(auction?.start_budget) + parseInt(auction?.lowest_bidding);

  const formSchema = z.object({
    bidding: z.preprocess(
      (val) => (typeof val === "string" ? Number(val) : val),
      z
        .number()
        .min(miniumAmountToBidding, s("miniumBidding") + miniumAmountToBidding)
    ),
  });

  const form = useForm({
    resolver: zodResolver(formSchema),
    defaultValues: {
      bidding: "",
    },
  });

  function onSubmit(values) {
    const formData = new FormData();
    formData.append("bidding", values.bidding);
    formData.append("product_id", auction?.product?.id);
    mutation.mutate(formData);
  }

  return (
    <Dialog className="max-w-full" open={showModal} onOpenChange={setShowModal}>
      <DialogTrigger asChild className="font-bold">
        <Button
          className="border-[#008ECC] hover:text-white hover:bg-[#008ECC] !px-[55px]"
          variant="outline"
        >
          {s("bidding")}
        </Button>
      </DialogTrigger>
      <DialogContent className="w-full !max-w-sm overflow-hidden">
        <DialogHeader>
          <DialogTitle className="text-center">
            {s("bidding")} {auction?.product?.title}
          </DialogTitle>
        </DialogHeader>
        <DialogDescription>
          <Form {...form}>
            <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
              <FormField
                control={form.control}
                name="bidding"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel> {s("offeredBidding")}</FormLabel>
                    <FormControl>
                      <Input
                        type="number"
                        min="1"
                        placeholder={s("minBidding") + miniumAmountToBidding}
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <Button
                disabled={mutation.isPending}
                variant="outline"
                className="border-[#008ECC] text-white bg-[#008ECC] hover:text-[#008ECC] hover:bg-white"
                type="submit"
              >
                {mutation.isPending && <Loader2 className="animate-spin" />}
                {s("sendOffer")}
              </Button>
            </form>
          </Form>
        </DialogDescription>
      </DialogContent>
    </Dialog>
  );
}
