import { useState } from "react";
import "react-phone-input-2/lib/high-res.css";
import OtpInputField from "./OtpInputField";
import { useNavigate } from "react-router-dom";
import useApiPost from "../../hooks/PostData";
import toast from "react-hot-toast";
import { useAppDispatch } from "../../utils/hooks";
import { VerifyOtpRes } from "../../types/ResType";
import Cookies from "js-cookie";
import { updateUserData } from "../../store/Slices/UserSlice";
import { ClipLoader } from "react-spinners";
import Countdown from "../../utils/Countdown";
import LoginLeftSections from "./LoginLeftSections";
import { useWebsiteSettings } from "../../store/api/useWebsiteSettings";
import { TbCopy } from "react-icons/tb";
import { useTheme } from "../../context/ThemeProvider";

export default function EnterOtp() {
  const navigate = useNavigate();
  // @ts-ignore
  const dataToSend = JSON.parse(sessionStorage.getItem("dataToSend"));
  const { loading, postData } = useApiPost();
  const [otp, setotp] = useState(import.meta.env.VITE_IS_DEMO == "true" ? "123456" : "");
  const dispatch = useAppDispatch();
  const { data: websiteSettings } = useWebsiteSettings();
  const [rememberMe, setRememberMe] = useState(false);
  const { theme } = useTheme();

  async function checkOtp() {
    if (otp.length != 6) {
      toast.error("Please Enter Otp");
      return;
    }

    try {
      let res: VerifyOtpRes;
      if (dataToSend?.email_id) {
        res = await postData("users/verfyOtp", {
          login_type: "email",
          platform: "web",
          country_code: dataToSend.country_code,
          email_id: dataToSend.email_id,
          otp: otp,
        });
      } else {
        res = await postData("users/verfyOtp", {
          login_type: "phone",
          platform: "web",
          country_code: dataToSend.country_code,
          mobile_num: dataToSend.mobile_num,
          otp: otp,
        });
      }

      if (res && res.status == true) {
        // if (rememberMe) {
        // Store token permanently (e.g., for 30 days)
        Cookies.set("whoxa_web_token", res.data.token, { expires: 30 });
        // } else {
        //   // Store token for the current session only
        //   Cookies.set("whoxa_web_token", res.data.token);
        // }

        dispatch(updateUserData(res.data.user));
        toast.success("Otp Verified");
        if (
          res.data.user.first_name == "" ||
          res.data.user.last_name == "" ||
          res.data.user.user_name == "" ||
          res.data.user.gender == ""
        ) {
          navigate("/user-details");
          // return;
        } else if (res.data.user.profile_pic == "") {
          navigate("/select-profile");
        } else {
          window.location.pathname = "/chat";
        }

        // navigate("/chat");
        // checkWichFieldIsEmpty(res.data, navigate);
        // let field = checkWichFieldIsEmpty(data.data);
        // console.log(field);
        // }
      } else {
        toast.error("Invalid Otp!");
      }
    } catch (error) {
      console.warn(error);
      toast.error("Invalid Otp!");
      // toast.error((error as Error).message);
    }
  }

  const handleReset = () => {
    console.log("OTP Resend triggered");
    // Add your resend OTP logic here
  };

  return (
    <div className="grid min-h-screen w-screen bg-white text-black lg:grid-cols-2">
      {/* Sign in Left side ====================================================================================*/}
      <LoginLeftSections />

      {/* Sign in Right side ====================================================================================*/}
      <div
        className="relative col-span-1 flex h-full w-full flex-col items-center justify-center bg-cover bg-center"
        style={{
          backgroundImage: `url(${"/Home/Login_page.jpg"})`,
        }}
      >
        <img
          className="absolute right-5 top-5 w-20 xl:w-28"
          src={
            theme === "dark"
              ? websiteSettings?.data.web_logo_dark
              : websiteSettings?.data.web_logo_light
          }
          alt=""
        />
        <div className="mx-auto w-[90%] max-w-[30rem] space-y-7 rounded-2xl p-5 shadow-[rgba(17,_17,_26,_0.1)_0px_0px_16px] lg:p-10 2xl:max-w-[35rem] 2xl:p-16">
          {/* <div className="flex">
            <h4 className="mr-3 text-xl font-medium lg:text-3xl">Welcome </h4>
            <img className="h-8 w-8" src="/LightIcons/hii.png" alt="" />
          </div> */}
          <div className="text-lg lg:text-2xl">
            Hello welcome to {websiteSettings?.data.app_name}
          </div>


          {import.meta.env.VITE_IS_DEMO == "true" ?
            <div className="bg-[#FFEDAB] rounded-xl text-center p-4">
              <div>Note: In this demo version Use the OTP</div>
              <b>123456</b>
            </div>
            :
            <div className="text-[#3A3A3A]">
              Enter the 6-digit OTP sent to{" "}
              <div className="flex gap-2">
                {dataToSend?.email_id ? (
                  <div className="font-bold"> {dataToSend.email_id}</div>
                ) : (
                  <>
                    <div className="font-bold">
                      {" "}
                      {dataToSend.country_code} {dataToSend.mobile_num}
                    </div>
                    <div
                      onClick={() => {
                        navigate(-1);
                      }}
                      className="cursor-pointer text-themeColor underline"
                    >
                      Change Number
                    </div>
                  </>
                )}
              </div>
            </div>
          }
          {/* Enter Otp ====================================================================================*/}
          <div className="space-y-5">
            <OtpInputField
              checkOtp={checkOtp}
              setotpPerant={setotp}
              externalOtp={otp}
            />
            {/* <div className="ml-auto mr-3 w-fit cursor-pointer text-[#FBCA16]">
              Resend OTP
            </div>
            <div className="text-center text-secondary">
              <Countdown time={120} onReset={handleReset} />
              </div> */}
            <Countdown
              time={Number(sessionStorage.getItem("countdownTime") || "120")}
              onReset={handleReset}
            />
            {/* Remember me */}
            {/* <div>
              <label className="flex items-center">
                <input
                  className="h-4 w-4 accent-[#FCC604]"
                  type="checkbox"
                  checked={rememberMe}
                  onChange={(e) => setRememberMe(e.target.checked)}
                />
                <span className="select-none pl-2 text-sm">Remember Me</span>
              </label>
            </div> */}
          </div>

          <button
            onClick={() => {
              checkOtp();
            }}
            className={`primary-gradient relative h-12 w-full overflow-hidden rounded-lg px-4 py-2 text-base font-medium outline-none lg:px-9 lg:text-lg`}
          >
            {loading ? (
              <div className="px-5">
                <ClipLoader color="black" size={23} />
              </div>
            ) : (
              <span className="">{"Login"}</span>
            )}
          </button>
        </div>
        {/* <div className="mx-auto mt-5 w-[90%] max-w-[30rem] rounded-xl bg-[#FFEDAB] p-4 2xl:max-w-[35rem]">
          <div className="font-semibold">For Demo</div>
          <hr className="my-3 border-t border-[#D8D8D8]" />
          <div>
            <span>Mobile Number : </span>
            <span>+1 5628532467</span>
          </div>
          <div>
            <span>Otp : </span>
            <span>123456</span>
          </div>
        </div> */}
        {import.meta.env.VITE_IS_DEMO == "true" && (
          <div className="mx-auto mt-5 w-[90%] max-w-[30rem] rounded-xl bg-[#FFEDAB] p-4 2xl:max-w-[35rem]">
            <div className="font-semibold">For Demo</div>
            <hr className="my-3 border-t border-[#D8D8D8]" />
            <div className="flex justify-between">
              {dataToSend?.email_id ? (
                <div className="flex w-full justify-between">
                  <div>
                    <span>Email Id : </span>
                    <span>whoxa@demo.com</span>
                  </div>
                  <div
                    onClick={() => {
                      setotp("123456");
                    }}
                    className="cursor-pointer"
                  >
                    <TbCopy className="text-xl" />
                  </div>
                </div>
              ) : (
                <div className="flex w-full justify-between">
                  <div>
                    <span>Mobile Number : </span>
                    <span>+1 5628532467</span>
                  </div>
                  <div
                    onClick={() => {
                      setotp("123456");
                    }}
                    className="cursor-pointer"
                  >
                    <TbCopy className="text-xl" />
                  </div>
                </div>
              )}
            </div>
            <div>
              <span>Otp : </span>
              <span>123456</span>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
