"use client";
import LoginStep from "@comp/Login/LoginStep";
import SignUp from "@comp/Login/SignUp";
import VerifyCodeStep from "@comp/Login/VerifyCodeStep";
import AppContext from "@ctx/AppContext";
import Image from "next/image";
import { useRouter } from "next/navigation";
import Chapar from "plugins/Chapar";
import { useContext, useState } from "react";
import { toast } from "react-toastify";
import logo from "../../../public/images/logo.png";
import Head from "next/head";

const Login = () => {
  const CTX = useContext(AppContext);

  const [phoneNumber, setPhoneNumber] = useState("");
  const [verifyCode, setVerifyCode] = useState("");
  const [firstName, setFirstName] = useState("");
  const [lastName, setLastName] = useState("");
  const [stepLogin, setStepLogin] = useState(0);

  const router = useRouter();

  const ConfirmPhoneNumber = async () => {
    CTX.setLoading(true);
    try {
      const data = await Chapar.get(
        `${process.env.NEXT_PUBLIC_API_URL}/auth/verifycode?phoneNumber=${phoneNumber}`
      );
      setStepLogin(1);
      localStorage.removeItem("token");
      CTX.setLoading(false);
    } catch ({ error, status }) {
      toast.error("  اطلاعات را صحیح وارد کنید ", {
        position: "bottom-right",
        closeOnClick: true,
      });
      CTX.setLoading(false);
    }
  };

  const LoginWhitVerifyCode = async () => {
    CTX.setLoading(true);

    try {
      const data = await Chapar.post(
        `${process.env.NEXT_PUBLIC_API_URL}/auth/login/code`,
        {
          userName: phoneNumber,
          password: null,
          verifyCode,
        }
      );

      localStorage.setItem("token", "Bearer " + data.access_token);

      if (data.user.signUpStatus == 1) {
        setStepLogin(2);
      } else if (data.user.signUpStatus == 10) {
        CTX.setProfile(data.user);
        toast.success(`  ${data.user.firstName}  جان خوش اومدی `, {
          position: "bottom-right",
          closeOnClick: true,
        });

        router.push("/profile");
      }

      CTX.setLoading(false);
    } catch ({ error, status }) {
      toast.error(`${error?.response?.data?.message}`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      CTX.setLoading(false);
    }
  };

  const SignUpLogin = async () => {
    CTX.setLoading(true);

    try {
      const data = await Chapar.post(
        `${process.env.NEXT_PUBLIC_API_URL}/auth/signup`,
        { lastName, firstName },
        {
          headers: {
            Authorization: localStorage.getItem("token"),
          },
        }
      );

      localStorage.removeItem("token");
      CTX.setLoading(false);
      CTX.setProfile(data.user);
      if (data.user.signUpStatus == 10) {
        // setProfile(data);

        toast.success(`  ${data.user.firstName}  جان خوش اومدی `, {
          position: "bottom-right",
          closeOnClick: true,
        });
        localStorage.setItem("token", "Bearer " + data.access_token);

        router.push("/profile");
      }
    } catch ({ error, status }) {
      toast.error(`${error?.response?.data?.message}`, {
        position: "bottom-right",
        closeOnClick: true,
      });
      CTX.setLoading(false);
    }
  };

  return (
    <div className="bg-login">
      <div className="xs:w-11/12 lg:w-4/12 xl:w-3/12 mx-auto pt-[150px]">
        <div className="bg-white p-10 rounded-3xl">
          <div className=" flex justify-center">
            <div className="w-[100px]">
              <Image src={logo} className="mx-auto" alt="ورود و عضویت وسمه" />
            </div>
          </div>
          {stepLogin == 0 ? (
            <LoginStep
              phoneNumber={phoneNumber}
              setPhoneNumber={setPhoneNumber}
              ConfirmPhoneNumber={ConfirmPhoneNumber}
            />
          ) : stepLogin == 1 ? (
            <VerifyCodeStep
              phoneNumber={phoneNumber}
              verifyCode={verifyCode}
              setVerifyCode={setVerifyCode}
              LoginWhitVerifyCode={LoginWhitVerifyCode}
            />
          ) : stepLogin == 2 ? (
            <SignUp
              setLastName={setLastName}
              setFirstName={setFirstName}
              SignUpLogin={SignUpLogin}
            />
          ) : (
            ""
          )}
        </div>
      </div>
    </div>
  );
};

export default Login;
