"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 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 whatsappr from "@/public/assets/icons/whatsapp3.svg";
import Image from "next/image";
import Link from "next/link";
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")),
    property: z.string().optional(),
  });

function SinglePropertyForm({
  propertyId,
  whatsappNumber,
}: {
  propertyId: string;
  whatsappNumber: string;
}) {
  // const [captchaToken, setCaptchaToken] = useState<string | null>(null);
  const t = useTranslations("SingleProperty");

  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: "",
      // captchaToken: "",
      property: "",
    },
  });

  const { mutate, isPending } = useMutation({
    mutationFn: (data: FormValues) =>
      apiServiceCall({ url: "quick-enquiry", body: data, method: "POST" }),
    onSuccess: () => {
      reset();
      toast.success(t("form_success_message"));
    },
    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) => {
    data.property = propertyId;
    mutate(data);
  };

  return (
    <>
      <div className="shadow-[0px_14px_15px_1px_rgba(0,_0,_0,_0.1)]    xl:w-[384px] p-3 rounded-2xl ">
        <form onSubmit={handleSubmit(onSubmit)} className="h-full text-dark">
          <h3 className=" text-[24px] font-normal mb-5 ">
            {t("Send Us a Message")}
          </h3>

          <div className="w-full relative flex flex-col gap-[25px] ">
            {/* <div className="absolute top-[50%] start-[12px]"></div> */}

            <div className="flex-1">
              <label className="text-[14px] font-extralight ">
                {t("Name")}
              </label>
              <input
                type="text"
                placeholder={t("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 className="text-[14px] font-extralight">
                {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 gap-[25px] my-5">
            {/* <div className="absolute top-[50%] start-[12px]"></div> */}

            <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>

          {/* <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> */}

          <div className="flex flex-col gap-4">
            <button
              type="submit"
              // disabled={isPending || !captchaToken}
              className="h-[53px] w-full bg-primary text-white py-2 px-4 rounded-lg hover:bg-white hover:text-primary hover:border hover:border-primary transition-colors duration-200 disabled:opacity-70 disabled:cursor-not-allowed"
            >
              {isPending ? t("Sending") : t("submit")}
            </button>

            <div className=" flex items-center gap-3 justify-center">
              <span className=" border-b-[1px] border-lightstroke w-[154px]"></span>
              <span className="text-paragraph text-[20px] font-light leading-[100%]">
                or
              </span>
              <span className=" border-b-[1px] border-lightstroke w-[154px]"></span>
            </div>

            <Link
              href={`https://wa.me/${whatsappNumber}`}
              className=" flex justify-center items-center gap-[10px] w-full h-[53px] bg-white border border-primary text-primary py-2 px-4 rounded-lg hover:bg-primary hover:text-white transition-colors duration-200 disabled:opacity-70 disabled:cursor-not-allowed"
            >
              <div>
                <Image src={whatsappr} alt="whatsapp icon" />
              </div>
              Conact Via Whatsapp
            </Link>
          </div>
        </form>
      </div>
    </>
  );
}

export default SinglePropertyForm;
