"use client";
/*
  Contact Us Form Component
  - Form for contact us
*/
import { AppDispatch } from "@/redux/store";
import { sendContactUsMessage } from "@/redux/thunks/ContactUs/contact-us.thunk";
import { setFirstCharCapital } from "@/src/utils/commonFunctions";
import { REGEX } from "@/src/utils/commonVariables";
import Routes from "@/src/utils/RouteConstants";
import { zodResolver } from "@hookform/resolvers/zod";
import { parsePhoneNumberFromString } from 'libphonenumber-js';
import Image from "next/image";
import Link from "next/link";
import React, { useState } from "react";
import { Controller, useForm } from "react-hook-form";
import { useDispatch } from "react-redux";
import { z } from "zod";
import CheckGif from "../../../../public/images/check-gif.gif";
import PhoneInputComponent from "../../PhoneInput/PhoneInput";
import styles from "./ContactForm.module.scss";

// Contact Us Form Props
interface ContactUsFormProps {
  FormContent: {
    LABEL: {
      FIRST_NAME: string;
      LAST_NAME: string;
      EMAIL: string;
      PHONE: string;
      DESCRIPTION: string;
    };
    PLACEHOLDER: {
      FIRST_NAME: string;
      LAST_NAME: string;
      EMAIL: string;
      PHONE: string;
      DESCRIPTION: string;
    };
    SEND: string;
  };
}

interface Option {
  value: string;
  label: string;
}
// Define options with type
const options: Option[] = [
  { value: "US", label: "US" },
  { value: "SEA", label: "SEA" },
  { value: "EU", label: "EU" },
  { value: "AUS", label: "AUS" },
  { value: "NZ", label: "NZ" },
];

const ContactUsForm: React.FC<ContactUsFormProps> = ({ FormContent }) => {
  const dispatch = useDispatch<AppDispatch>();
  // Code for passing the option dynamically
  const [selectedOption, setSelectedOption] = useState<Option>(options[0]);
  const [selectedCountry, setSelectedCountry] = useState('at');
  const [isSuccess, setIsSuccess] = useState(false);
  const [phone, setPhone] = useState('');
  const [phoneNumberFormated, setPhoneNumberFormatted] = useState('');
  const [isShowPhoneNumberError, setIsShowPhoneNumberError] = useState(false);

  const schema = z.object({
    firstName: z.string().min(1, { message: "First name is required" }).trim(),
    lastName: z.string().min(1, { message: "Last name is required" }).trim(),
    email: z
      .string()
      .min(1, { message: "Email is required" })
      .regex(REGEX.EMAIL, { message: "Email is invalid" }),
    mobileNumber: z.string({ message: "Phone number is required" }).min(1, { message: "Phone number is required" }),
    message: z.string().min(1, { message: "Description is required" }).trim(),
    honeypot: z.string().max(0, "Form submission failed"),
  }).superRefine(async (data, ctx) => {
    const phoneNumber = parsePhoneNumberFromString(data.mobileNumber);

    if (!phoneNumber || !phoneNumber.isValid()) {
      ctx.addIssue({
        path: ['mobileNumber'],
        message: 'Phone number is invalid',
        code: z.ZodIssueCode.custom,
      });
    }
  });

  const {
    register,
    handleSubmit,
    formState: { errors },
    trigger,
    control,
    reset,
    clearErrors,
    setError,
    setValue
  } = useForm<z.infer<typeof schema>>({
    resolver: zodResolver(schema),
    mode: "onChange", // Enable validation on change
    delayError: 500, // Add a small delay to prevent validation on every keystroke
  });

  // const mobileNumberValidation = () => {
  //   return new Promise((resolve) => {
  //     const phoneNumber = parsePhoneNumberFromString(phoneNumberFormated)
  //     if (phoneNumber && phoneNumber.isValid()) {
  //       setIsShowPhoneNumberError(false)
  //       resolve(true)
  //     } else {
  //       setIsShowPhoneNumberError(true)
  //       resolve(false)
  //     }
  //   })
  // }


  const onSubmit = (data: z.infer<typeof schema>) => {

    // If honeypot is filled, it's likely a bot - silently reject or log
    if (data.honeypot) {
      return;
    }

    // Process legitimate form submission
    const { honeypot, ...formData } = data;

    const payload: any = {
      ...formData,
      countryCode: selectedCountry,
    };

    dispatch(
      sendContactUsMessage(payload, () => {
        setIsSuccess(true);
        reset();
        setSelectedCountry('at');
        setPhone('43')
        setValue('mobileNumber', '+43')
        setIsShowPhoneNumberError(false)
      })
    );
  };

  // Handle phone input type to allow valid phone characters
  const handlePhoneInput = (e: React.ChangeEvent<HTMLInputElement>) => {
    // Allow only numbers, plus sign, parentheses, spaces and hyphens
    const value = e.target.value;
    const filteredValue = value.replace(/[^\d()+\- ]/g, "");
    e.target.value = filteredValue;

    // Trigger validation after changing the value
    trigger("mobileNumber");
  };

  return (
    <>
      <form onSubmit={handleSubmit(onSubmit)}>
        <div className="RowWrap">
          <div className="InputWrapper">
            <label htmlFor="firstName">{FormContent.LABEL.FIRST_NAME}</label>
            <input
              id="firstName"
              {...register("firstName", {
                onChange: (e) => {
                  setValue("firstName", setFirstCharCapital(e)),
                    trigger("firstName")
                }
              })}
              placeholder={FormContent.PLACEHOLDER.FIRST_NAME}
              type="text"
            />
            {/* error message text */}
            {errors.firstName && (
              <p className="error-msg">{errors.firstName?.message}</p>
            )}
          </div>
          <div className="InputWrapper">
            <label htmlFor="lastName">{FormContent.LABEL.LAST_NAME}</label>
            <input
              id="lastName"
              {...register("lastName", {
                onChange: (e) => {
                  setValue("lastName", setFirstCharCapital(e)),
                    trigger("lastName")
                }
              })}
              placeholder={FormContent.PLACEHOLDER.LAST_NAME}
              type="text"
            />
            {/* error message text */}
            {errors.lastName && (
              <p className="error-msg">{errors.lastName?.message}</p>
            )}
          </div>
        </div>
        <div className="InputWrapper">
          <label htmlFor="email">{FormContent.LABEL.EMAIL}</label>
          <input
            id="email"
            {...register("email", {
              onChange: () => trigger("email"),
            })}
            placeholder={FormContent.PLACEHOLDER.EMAIL}
            type="email"
          />
          {/* error message text */}
          {errors.email && <p className="error-msg">{errors.email?.message}</p>}
        </div>
        <div className="InputWrapper">
          <label htmlFor="mobileNumber">{FormContent.LABEL.PHONE}</label>
          <div
            className={`CountryDropdown DropdownMainBox flex gap-0 items-stretch`}
          >
            {/* {<Select
                        options={options}
                        value={selectedOption}
                        onChange={(option) => setSelectedOption(option as Option)}
                        className={`customDropdown shrink-0 !max-w-[200px]`}
                    />}
                    <input id="mobileNumber"
                        {...register("mobileNumber", {
                            onChange: (e) => handlePhoneInput(e)
                        })}
                        placeholder={FormContent.PLACEHOLDER.PHONE}
                        type="tel" // Changed from number to tel for better phone input handling
                    /> */}
            <Controller
              name="mobileNumber"
              control={control}

              render={({ field: { onChange } }) => (
                <>
                  <PhoneInputComponent onChange={onChange} setPhoneNumberFormatted={setPhoneNumberFormatted} selectedCountry={selectedCountry} setSelectedCountry={setSelectedCountry} phone={phone} setPhone={setPhone} />
                </>
              )}
            />
          </div>
          {/* error message text */}
          {errors.mobileNumber && (
            <p className="error-msg">{errors.mobileNumber?.message}</p>
          )}
        </div>
        <div className="InputWrapper">
          <label htmlFor="message">{FormContent.LABEL.DESCRIPTION}</label>
          <textarea
            id="message"
            {...register("message", {
              onChange: () => trigger("message"),
            })}
            placeholder={FormContent.PLACEHOLDER.DESCRIPTION}
          ></textarea>
          {/* error message text */}
          {errors.message && (
            <p className="error-msg">{errors.message?.message}</p>
          )}
        </div>
        <div
          className="InputWrapper"
          style={{ display: "none", position: "absolute", left: "-9999px" }}
        >
          <input
            id="honeypot"
            {...register("honeypot")}
            aria-hidden="true"
            tabIndex={-1}
            autoComplete="off"
            type="text"
          />
        </div>
        <div className={`mt-[20px] xl:mt-[25px]`}>
          <button name="submit" type="submit" className={`w-full SecondaryBtn`}>
            {FormContent.SEND}
          </button>
        </div>
      </form>
      {isSuccess && (
        <div
          className={`CustomPopup commonPopup flex items-center fixed top-0 left-0 justify-center h-dvh w-full z-9999`}
        >
          <div
            className={`${styles.overlayBackground} h-full w-full absolute top-0 left-0`}
          ></div>
          <div
            className={`popupWrapper max-w-[90%] z-[3] h-fit w-[588px] relative`}
          >
            <button
              type="button"
              className={`PopupCloseBtn SecondaryBtn !p-0 absolute right-0 top-0 z-1 !w-[57px] !h-[57px] rounded-full`}
              onClick={() => setIsSuccess(false)}
            >
              <i className={`Icon IconCross !bg-white w-[14px] h-[14px]`}></i>
            </button>
            <div className={`popupBox w-full`}>
              <div className="popup-wrapper-body p-4 md:p-5 lg:p-6">
                <div className="swalContent">
                  <div
                    className={`w-full max-h-[calc(100vh-260px)] md:max-h-[calc(100vh-260px)] overflow-auto`}
                  >
                    <Image
                      className="!w-[100px] !h-[100px] mx-auto mb-4"
                      width={100}
                      height={100}
                      src={CheckGif}
                      alt="profile-created"
                    />
                    <div className="text-center max-w-[450px] mx-auto">
                      <h4 className={`!text-center title !mb-2`}>
                        Submission Successful!
                      </h4>
                      <p className={`!text-center fs-16 text-grey667Color`}>
                        Thank you for your submission. We have received your
                        information and will process it shortly. You will
                        receive a confirmation email within the next few
                        minutes.
                      </p>
                      <Link className="SecondaryBtn" href={Routes.FIND_A_HOME}>Find a home</Link>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      )}
    </>
  );
};

export default ContactUsForm;
