"use client";

import { useEffect, useState } from "react";
import "./ConfirmEmailForm.scss";
import { apiInstance } from "@/shared/config/apiConfig";
import { useRouter } from "next/navigation";
import Loader from "@/shared/ui/components/Loader/Loader";

interface IConfirmEmailFormProps {
  email: string;
}

const ConfirmEmailForm: React.FC<IConfirmEmailFormProps> = ({
  email,
}: IConfirmEmailFormProps) => {
  const router = useRouter();
  const [otp, setOtp] = useState(new Array(6).fill(""));
  const [seconds, setSeconds] = useState<number>(0);
  const [minutes, setMinutes] = useState<number>(1);
  const [error, setError] = useState<string>("");
  const [loader, setLoader] = useState<boolean>(false);

  const handleChange = (e: any, index: number) => {
    if (isNaN(+e.target.value)) return false;

    setOtp([
      ...otp.map((data, i) => (i === index ? e.target.value : data)),
    ]);

    if (e.target.value && e.target.nextSibling) {
      e.target.nextSibling.focus();
    } else if (!e.target.value && e.target.previousSibling) {
      e.target.previousSibling.focus();
    }
  };

  const handleSubmit: React.MouseEventHandler<
    HTMLFormElement
  > = async (e) => {
    e.preventDefault();

    const code = {
      code: +otp.join(""),
    };

    try {
      setLoader(true);

      const response = await apiInstance.post(
        "/users/confirm/",
        code
      );

      if (response.status === 200 || response.status === 201) {
        router.push("/sign-in");
      }
    } catch (error) {
      setError("Возникла ошибка");
    } finally {
      setLoader(false);
    }
  };

  const handleClick = async () => {
    const data = {
      email,
    };
    const response = await apiInstance.post(
      "/users/resend_code/",
      data
    );

    if (response.status === 200 || response.status === 201) {
      setMinutes(1);
    }
  };

  useEffect(() => {
    if (minutes === 0 && seconds === 0) return;

    const timer = setInterval(() => {
      if (seconds === 0) {
        setMinutes((prev) => Math.max(0, prev - 1));
        setSeconds(59);
      } else {
        setSeconds((prev) => prev - 1);
      }
    }, 1000);

    return () => clearInterval(timer);
  }, [minutes, seconds]);

  return (
    <form onSubmit={handleSubmit} className="confirm-email-form">
      <div className="confirm-email-form__inputs">
        <label>Код подтверждения</label>
        <div className="confirm-email-form__inputs-wrapper">
          {otp.map((data, index) => (
            <input
              id={data ? "confirm-email-form__input-active" : ""}
              key={index}
              onChange={(e) => handleChange(e, index)}
              value={data}
              maxLength={1}
              type="text"
            />
          ))}
        </div>
        {error ? (
          <p className="confirm-email-form__error">{error}</p>
        ) : null}
      </div>
      <button
        disabled={otp.join("").length === 6 ? false : true}
        id={`confirm-email-form__send-code${
          otp.join("").length === 6 ? "_active" : ""
        }`}
        type="submit"
      >
        {loader ? <Loader /> : "Подтвердить"}
      </button>

      <p className="confirm-email-form__timer">
        Отправить код повторно через{" "}
        <span>
          0{minutes}:
          {seconds.toString().length === 1 ? `0${seconds}` : seconds}
        </span>
      </p>

      <button
        type="button"
        onClick={handleClick}
        disabled={minutes === 0 && seconds === 0 ? false : true}
        id={`confirm-email-form__resend-code${
          minutes === 0 && seconds === 0 ? "_active" : ""
        }`}
      >
        {loader ? <Loader /> : "Отправить код повторно"}
      </button>
    </form>
  );
};

export default ConfirmEmailForm;
