"use client";
import ReCAPTCHA from "react-google-recaptcha";
import { useState, useRef } from "react";

export default function Callback1() {
  const [domain, setDomain] = useState("");
  const [email, setEmail] = useState("");
  const [captchaValue, setCaptchaValue] = useState(null);
  const [isLoading, setIsLoading] = useState(false);

  const recaptchaRef = useRef(null);

  const handleChange = ({ target: { name, value } }) => {
    if (name === "domain") {
      setDomain(value);
    } else if (name === "email") {
      setEmail(value);
    }
  };

  const handleCaptchaChange = (value) => {
    setCaptchaValue(value);
  };

  const handleSubmit = async (event) => {
    event.preventDefault();
    setIsLoading(true);
    try {
      const response = await fetch("/api/verifyreport", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ domain, email, captcha: captchaValue }),
      });
      const data = await response.json();
      if (response.ok) {
        sessionStorage.setItem("reportData", JSON.stringify({ domain, email }));

        const getReport = await fetch("/api/getreport", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({ websitename: domain, emailname: email }),
        });
        const reportResult = await getReport.json();

        if (getReport.ok) {
          try {
            const cryagentResponse = await fetch(
              "https://cryagent.pythonanywhere.com/submitrankrunnerschecker",
              {
                method: "POST",
                headers: {
                  "Content-Type": "application/json",
                },
                body: JSON.stringify({ email: email }),
              }
            );

            if (!cryagentResponse.ok) {
              console.error("Failed to submit to cryagent.pythonanywhere.com");
            }
          } catch (cryagentError) {
            console.error(
              "Error submitting to cryagent.pythonanywhere.com:",
              cryagentError
            );
          }

          sessionStorage.setItem("reportResult", JSON.stringify(reportResult));
          window.location.href = "/report";
        } else {
          console.error("API response:", reportResult);
          alert(reportResult.message);
        }
      } else {
        console.error("API response:", data);
        alert(data.message);
      }
      setIsLoading(false);
    } catch (error) {
      console.error("Error submitting form:", error);
      alert("An error occurred. Please try again later.");
      setIsLoading(false);
    }
  };

  return (
    <>
      <section className="call-back-area">
        <div className="container">
          <div className="row">
            <div className="col-lg-5">
              <div className="call-back-content">
                <div className="section-title white-title mb-10 tg-heading-subheading animation-style3">
                  <h2 className="text-custom-sizing-h2 title tg-element-title ">
                    Check your website's SEO performance
                  </h2>
                </div>
                <div className="shape">
                  <img
                    src="/assets/img/images/call_back_shape.png"
                    alt=""
                    data-aos="fade-right"
                    data-aos-delay={400}
                  />
                </div>
              </div>
            </div>
            <div className="col-lg-7">
              <div className="call-back-form">
                <form onSubmit={handleSubmit}>
                  <div className="row">
                    <div className="col-md-6">
                      <div className="form-grp">
                        <input
                          onChange={handleChange}
                          required
                          type="text"
                          name="domain"
                          value={domain}
                          placeholder="Website URL *"
                        />
                      </div>
                    </div>
                    <div className="col-md-6">
                      <div className="form-grp">
                        <input
                          onChange={handleChange}
                          required
                          type="email"
                          name="email"
                          value={email}
                          placeholder="Email Address *"
                        />
                      </div>
                    </div>
                    <div className="col-md-6">
                      <div className="form-grp">
                        {/* <ReCAPTCHA
                          ref={recaptchaRef}
                          sitekey={process.env.NEXT_PUBLIC_RECAPTCHA_SITE_KEY}
                          onChange={handleCaptchaChange}
                        /> */}
                      </div>
                    </div>
                    <div className="col-md-6">
                      {!isLoading && (
                        <button type="submit" className="btn">
                          <span>Check Now</span>
                        </button>
                      )}
                      {isLoading && (
                        <button type="submit" className="btn" disabled>
                          <div
                            class="spinner-border spinner-border-sm text-light"
                            role="status"
                          >
                            <span class="sr-only">Loading...</span>
                          </div>
                        </button>
                      )}
                    </div>
                  </div>
                </form>
              </div>
            </div>
          </div>
        </div>
      </section>
    </>
  );
}
