"use client";

import { useForm } from "react-hook-form";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
// import { Button, Input, Form, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui"
import postData from "@/api/post-data";
import { useLocale, useTranslations } from "next-intl";
import {
  Form,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input"; // Correct path for ShadCN Input
import SubmitButton from "../../shared/SubmitButton";
import { useState } from "react";
import { toastError, toastSuccess } from "@/services/custom-toast";
import { FaSpinner } from "react-icons/fa";

export default function AddLabel({ success }) {
  const locale = useLocale();
  const t = useTranslations("vendor");
  const [isLoading, setIsLoading] = useState(false);
  const e = useTranslations("form-errors");
  const form = useForm({
    resolver: zodResolver(
      z.object({
        label: z.string().min(1, e("required")),
      })
    ),
    defaultValues: { label: "" },
  });

  async function onSubmit(values) {
    const formData = new FormData();
    formData.append("label", values.label);
    setIsLoading(true);
    const { message, error } = await postData({
      endPoint: "/user/products/addtional-details/label",
      body: formData,
      locale,
    });
    if (error) {
      setIsLoading(false);
      toastError(message);
    }
    if (!error) {
      setIsLoading(false);
      toastSuccess(message);
      success(true);
    }
    setIsLoading(false);
  }

  return (
    <Form {...form}>
      <form
        onSubmit={form.handleSubmit(onSubmit)}
        className="flex  gap-2  max-md:w-full"
      >
        <FormField
          control={form.control}
          name="label"
          render={({ field }) => (
            <FormItem className="w-64 ">
              <Input
                placeholder={t("enterlabel")}
                {...field}
                className="max-md:h-10"
              />
              <FormMessage />
            </FormItem>
          )}
        />
        <button
          type="submit"
          disabled={isLoading}
          className="w-auto md:w-28 h-10 md:h-12  btn btn-btnColor  text-white p-2 rounded-md"
        >
          {isLoading ? (
            <FaSpinner className="animate-spin m-auto" />
          ) : (
            t("send")
          )}
        </button>{" "}
      </form>
    </Form>
  );
}
