"use client";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { FaArrowRight, FaSpinner } from "react-icons/fa";
import { Input } from "@/components/ui/input"; // Adjust this import based on ShadCN's Input component location
import { Button } from "@/components/ui/button";
import { useLocale, useTranslations } from "next-intl";
import postData from "@/api/post-data";
import { toastError, toastSuccess } from "@/services/custom-toast";


export default function Newsletter() {
  const locale = useLocale();
  const t = useTranslations("form-labels")
  const e = useTranslations("form-errors")
  const f = useTranslations("footer")

  const schema = z.object({
    email: z.string().email(e("email")),
  });
  const { register, handleSubmit, formState: { errors, isSubmitting } } = useForm({
    resolver: zodResolver(schema),
  });

  const onSubmit = async (data) => {
    const formData = new FormData();
    formData.append("email", data.email);
    const response = await postData(
      {
        endPoint: "/subscribe",
        locale,
        body: formData
      }
    )
    if (!response.error) {
      if (response?.status == "success") {
        toastSuccess(f("subscriptionSuccess"))
      } else {
        toastError(f("subscriptionError"))
      }

    }
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)} >
      <div className="relative">
        <Input
          type="email"
          {...register("email")}
          placeholder={t("email")}
          className={`py-3 border-2 w-full ps-16 focus-visible:ring-black rounded-none `}
        />
        <Button
          type="submit"
          className="absolute  rounded-none top-1/2 -translate-y-1/2 start-0 flex items-center justify-center bg-black text-white "
        >
          {isSubmitting ?
            <FaSpinner size={18} className=" animate-spin" />
            :
            <FaArrowRight size={18} />}
        </Button>
      </div>
      {errors.email && (
        <p className="text-red-500 mt-1">{errors.email.message}</p>
      )}
    </form>

  );
}
