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

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);

      console.log(data);

      if (data.user.signUpStatus == 1) {
        setStepLogin(2);
      } else if (data.user.signUpStatus == 10) {
        // setProfile(data);
        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"),
          },
        }
      );

      CTX.setLoading(false);

      if (data.user.signUpStatus == 10) {
        // setProfile(data);

        toast.success(`  ${data.user.firstName}  جان خوش اومدی `, {
          position: "bottom-right",
          closeOnClick: true,
        });
        localStorage.setItem("token", 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" />
            </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;
