import InputText from "../utils/inputText";
import style from "./contactForm.module.css";
import { customerApi } from "@/api/api";
import Loader from "@/components/utils/loader";
import { useCallback, useState } from "react";
import ReCAPTCHA from "react-google-recaptcha";
import { useRef } from "react";
import { usePhoneValidation } from "@/customHook/useValidation";
import { useDispatch, useSelector } from "react-redux";
import { accountStoreActions } from "@/store/account";
import { GoogleReCaptcha } from "react-google-recaptcha-v3";
import { Mail, MailOutlineOutlined, Send } from "@mui/icons-material";

const ContactForm = () => {
  const [loader, setLoader] = useState(false);
  const [error, setError] = useState("");
  const [refreshReCaptcha, setRefreshReCaptcha] = useState(false);
  const [captcha, setCaptcha] = useState();
  const [phoneNo, setPhoneNo] = useState();
  const [message, setMessage] = useState();
  const [subject, setSubject] = useState();
  const [successMessage, setSuccessMessage] = useState(null);
  const phoneValidation = usePhoneValidation(phoneNo);
  const [phoneError, setPhoneError] = useState(null);
  const account = useSelector((state) => state.accountStore);

  const dispatch = useDispatch();

  const onSubmit = async (e) => {
    try {
      e.preventDefault();
      if (!account.loggedIn) {
        dispatch(accountStoreActions.openSignInUI({ signInUI: true }));
        return 0;
      }
      setError("");
      setPhoneError(false);
      if (phoneValidation.value === false) {
        setError("Phone Number Invalid");
        setPhoneError(true);
        return 0;
      }
      if (!captcha) {
        setError("Complete Captcha");
        return 0;
      }
      if (loader) return;
      setError("");
      setLoader(true);
      let body = "";
      body = body + `Subject: ${subject} \n\n`;
      body = body + `${message}`;
      const response = await customerApi.post(
        "/form/submit",
        {
          subject: "Contact Request",
          phone: phoneNo,
          body: body,
          token: captcha,
        },
        { withCredentials: true }
      );
      if (response.data.success) {
        if (response.data.success === true) {
          setSuccessMessage(true);
        }
      } else {
        setError("Failed Due To Unknown Reason, Contact Administrator");
        setRefreshReCaptcha((prev) => !prev);
      }
      setLoader(false);
    } catch (err) {
      setLoader(false);
      setRefreshReCaptcha((prev) => !prev);
      console.log("err: ", err);
      setError("Failed!, Refresh And Try Again");
    }
  };

  const onVerify = useCallback((token) => {
    setCaptcha(token);
  }, []);

  return (
    <div className={style.contactForm_form}>
      <div className={style.head_section}>
        <h1 className={`${style.primary_heading}`}>Send us a Message</h1>
        <MailOutlineOutlined />
      </div>

      {!successMessage && (
        <div className={style.section_box}>
          <form onSubmit={onSubmit}>
            <div className={style.input_section}>
              <div className={style.input_grid}>
                <div>
                  <p>Subject</p>
                  <InputText
                    type="text"
                    name="subject"
                    placeholder="Enter Subject"
                    getValue={(value) => {
                      setSubject(value);
                    }}
                    required={true}
                    customClass={style.customInputClass}
                  />
                </div>
                <div>
                  <p>Phone</p>
                  <InputText
                    type="tel"
                    name="Phone"
                    placeholder="Enter Phone Number"
                    maxLength={10}
                    minLength={10}
                    getValue={(value) => {
                      setPhoneNo(value);
                    }}
                    required={true}
                    customClass={style.customInputClass}
                    error={phoneError}
                  />
                </div>
              </div>
              <div>
                <p>Message</p>
                <InputText
                  inputType="textarea"
                  name="body"
                  rows={5}
                  placeholder="Enter Message"
                  getValue={(value) => {
                    setMessage(value);
                  }}
                  required={true}
                />
              </div>
              <center>
                <GoogleReCaptcha
                  onVerify={onVerify}
                  refreshReCaptcha={refreshReCaptcha}
                />
              </center>
              <div className={style.status}>
                {error && (
                  <div className={`${style.error_status}`}>{error}</div>
                )}
              </div>
              {loader ? (
                <button
                  type="button"
                  className={`primary_btn_no_animation ${style.button}`}
                  disabled={true}
                >
                  <Loader className={style.submitLoader} />
                </button>
              ) : (
                <button
                  type="submit"
                  className={`primary_btn_no_animation ${style.button}`}
                >
                  <Send />
                </button>
              )}
            </div>
          </form>
        </div>
      )}
      {successMessage && (
        <p className={`success ${style.successMessage}`}>
          Thank you for getting in touch! We appreciate you contacting us
        </p>
      )}
    </div>
  );
};

export default ContactForm;
