"use client";
import CustomSelect from "@/components/reusableComponent/CustomSelect";
import CostumPhoneInput from "@/components/reusableComponent/PhoneInput";
import apiServiceCall from "@/lib/apiServiceCall";
import { useMutation } from "@tanstack/react-query";
import React, { useState } from "react";
import ReCAPTCHA from "react-google-recaptcha";
import { Controller, useForm } from "react-hook-form";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { useTranslations } from "next-intl";
import toast from "react-hot-toast";

/* =======================
   Zod Schema (Translated)
======================= */
const getFormSchema = (t: any) =>
  z.object({
    name: z.string().min(1, t("errors.name_required")),
    email: z.string().email(t("errors.email_invalid")),
    phone: z.string().min(1, t("errors.phone_required")),
    subject: z.string().min(1, t("errors.subject_required")),
    message: z.string().min(1, t("errors.message_required")),
    // captchaToken: z.string().min(1, "Please verify you are not a robot"),
  });

function ContactUsForm() {
  const [captchaToken, setCaptchaToken] = useState<string | null>(null);
  const t = useTranslations("contactUs");

  const formSchema = getFormSchema(t);
  type FormValues = z.infer<typeof formSchema>;

  const {
    control,
    register,
    formState: { errors },
    handleSubmit,
    reset,
    setValue,
    setError,
    clearErrors,
  } = useForm<FormValues>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      name: "",
      email: "",
      phone: "",
      subject: "",
      message: "",
      // captchaToken: "",
    },
  });

  const { mutate, isPending } = useMutation({
    mutationFn: (data: FormValues) =>
      apiServiceCall({ url: "contact-us", body: data, method: "POST" }),
    onSuccess: () => {
      toast.success(t("form_success_message"));
      reset();
      setCaptchaToken(null);
    },
    onError: (error: any) => {
      toast.error(
        error?.message || t("errors.general_error")
      );
      console.log("Error submitting form:", error?.message);
    },
  });

  // const handleCaptchaChange = (token: string | null) => {
  //   if (token) {
  //     setValue("captchaToken", token);
  //     clearErrors("captchaToken");
  //     setCaptchaToken(token);
  //   } else {
  //     setError("captchaToken", {
  //       type: "manual",
  //       message: "Please verify you are not a robot",
  //     });
  //     setCaptchaToken(null);
  //   }
  // };

  const onSubmit = (data: FormValues) => {
    mutate(data);
  };

  return (
    <form
      onSubmit={handleSubmit(onSubmit)}
      className="w-full text-[#252525] h-auto"
    >
      <div className="w-full relative flex flex-col lg:flex-row gap-[25px]">
        {/* <div className="absolute top-[50%] start-[12px]"></div> */}

        <div className="flex-1">
          <label>{t("Full Name")}</label>
          <input
            type="text"
            placeholder={t("Full Name")}
            className="w-full px-1 pt-5 pb-2 flex-1 border-b-[2px] border-gray-200 outline-none placeholder:text-[14px]"
            {...register("name")}
          />
          {errors.name && (
            <p className="text-red-500 text-sm mt-1">
              {errors.name.message}
            </p>
          )}
        </div>

        <div className="flex-1">
          <label>{t("Email")}</label>
          <input
            type="text"
            placeholder={t("Email")}
            className="w-full px-1 pt-5 pb-2 flex-1 border-b-[2px] border-gray-200 outline-none placeholder:text-[14px]"
            {...register("email")}
          />
          {errors.email && (
            <p className="text-red-500 text-sm mt-1">
              {errors.email.message}
            </p>
          )}
        </div>
      </div>

      <div className="w-full relative flex flex-col lg:flex-row gap-[25px] my-5">
        <div className="flex-1">
          <Controller
            name="phone"
            control={control}
            render={({ field, fieldState }) => (
              <>
                <CostumPhoneInput
                  className="[&_.PhoneInputCountry]:!text-white"
                  label={t("Phone Number")}
                  value={field.value}
                  onChange={field.onChange}
                />
                {fieldState.error && (
                  <p className="text-red-500 text-sm mt-1">
                    {fieldState.error.message}
                  </p>
                )}
              </>
            )}
          />
        </div>

        <div className="flex-1">
          <label>{t("Subject")}</label>
          <input
            type="text"
            placeholder={t("Subject")}
            className="w-full px-1 pt-5 pb-3 flex-1 border-b-[2px] border-gray-200 outline-none placeholder:text-[14px]"
            {...register("subject")}
          />
          {errors.subject && (
            <p className="text-red-500 text-sm mt-1">
              {errors.subject.message}
            </p>
          )}
        </div>
      </div>

      <div className="w-full relative flex flex-col lg:flex-row gap-[2px]">
        {/* <div className="absolute top-[50%] start-[12px]"></div> */}
        <div className="flex-1">
          <label>{t("Message")}</label>
          <textarea
            placeholder={t("Message")}
            className="w-full px-1 py-5 flex-1 outline-none border-b-[2px] border-gray-200 placeholder:text-[14px]"
            {...register("message")}
          />
          {errors.message && (
            <p className="text-red-500 text-sm mt-1">
              {errors.message.message}
            </p>
          )}
        </div>
      </div>

      {/* <div className="my-5">
        <ReCAPTCHA
          sitekey="YOUR_SITE_KEY_HERE"
          onChange={handleCaptchaChange}
        />
        {errors.captchaToken && (
          <p className="text-red-500 text-sm mt-1">
            {errors.captchaToken.message}
          </p>
        )}
      </div> */}

      <button
        type="submit"
        // disabled={isPending || !captchaToken}
        className="w-full bg-[#5A0816] text-white py-2 px-4 rounded-lg hover:bg-[#4B0713] transition-colors duration-200 mt-5 disabled:opacity-70 disabled:cursor-not-allowed"
      >
        {isPending ? t("Sending") : t("Send")}
      </button>
    </form>
  );
}

export default ContactUsForm;
