"use client";
import fetchData from "@/api/fetch-data";
import postData from "@/api/post-data";
import { toastError, toastSuccess } from "@/services/custom-toast";
import { zodResolver } from "@hookform/resolvers/zod";
import { useQuery } from "@tanstack/react-query";
import { useLocale, useTranslations } from "next-intl";
import { useForm } from "react-hook-form";
import { z } from "zod";
import AlertWarning from "../ui/shared/AlertWarning";
import ContactRedesignThree from "../ui/shared/ContactRedesignThree";

export default function ContactUs() {
  const error = useTranslations("form-errors");
  const locale = useLocale();

  const form = useForm({
    defaultValues: {
      message: "",
      subject: "",
      email: "",
      name: "",
    },
    resolver: zodResolver(
      z.object({
        message: z
          .string({ errorMap: () => ({ message: error("required") }) })
          .min(1),
        subject: z.string().optional(),
        name: z
          .string({ errorMap: () => ({ message: error("required") }) })
          .min(1),
        email: z
          .string({ errorMap: () => ({ message: error("email") }) })
          .email(),
      })
    ),
  });

  const {
    setError,
    formState: { isSubmitting },
  } = form;

  async function onSubmit(data) {
    const formData = new FormData();
    formData.append("message", data.message);
    formData.append("subject", data.subject);
    formData.append("name", data.name);
    formData.append("email", data.email);
    const { error, message, errors } = await postData({
      endPoint: "/contact-us",
      body: formData,
      locale,
    });
    if (error) {
      for (const [key, value] of Object.entries(errors)) {
        setError(
          key,
          {
            type: "server",
            message: value,
          },
          { shouldFocus: true }
        );
      }
      toastError(message);
      return;
    }
    toastSuccess(message);
    form.reset();
  }

  // Fetch Contact Data
  const { data, isLoading } = useQuery({
    queryKey: ["settings", locale],
    queryFn: async () => {
      return fetchData({ endPoint: "/settings", locale });
    },
    staleTime: 1000 * 60 * 5,
  });
  if (data?.error) return <AlertWarning text={data?.message} />;
  if (isLoading)
    return (
      <div className="flex items-center justify-center w-full  h-[40vh]">
        <div className="loader"></div>
      </div>
    );
  if (data?.error) return toastError(data?.message);
  if (!data?.error && data?.data?.length === 0)
    return <AlertWarning text={data?.message} />;

  return (
    <ContactRedesignThree
      data={data}
      form={form}
      onSubmit={onSubmit}
      isSubmitting={isSubmitting}
    />
  );
}
