import React, { useState, useEffect } from "react";
import "./Pincode.css";
import { FiDelete } from "react-icons/fi";
import { useNavigate } from "react-router-dom";
import { TG_USER_ID } from "../../constants/constants";
import { useTranslation } from "react-i18next";

const Pincode: React.FC = () => {
  const [pin, setPin] = useState("");
  const [step, setStep] = useState<"create" | "confirm" | "enter">("create");
  const [firstPin, setFirstPin] = useState<string | null>(null);
  const [error, setError] = useState(false);
  const navigate = useNavigate();
  const { t } = useTranslation();

  useEffect(() => {
    const storedPin = localStorage.getItem(`pincode-${TG_USER_ID}`);

    if (storedPin) {
      setStep("enter");
    }
  }, []);

  const handleDigit = (digit: string) => {
    if (pin.length < 4) setPin(pin + digit);
  };

  const handleDelete = () => {
    setPin(pin.slice(0, -1));
  };

  useEffect(() => {
    if (pin.length === 4) {
      if (step === "enter") {
        const storedPin = localStorage.getItem(`pincode-${TG_USER_ID}`);
        if (pin === storedPin) {
          sessionStorage.setItem(`pincode-${TG_USER_ID}`, pin);
          navigate("/home");
        } else {
          setError(true);
          setTimeout(() => {
            setPin("");
            setError(false);
          }, 1000);
        }
        return;
      }

      if (!firstPin) {
        setFirstPin(pin);
        setPin("");
        setStep("confirm");
      } else {
        if (firstPin === pin) {
          localStorage.setItem(`pincode-${TG_USER_ID}`, pin);
          sessionStorage.setItem(`pincode-${TG_USER_ID}`, pin);
          navigate("/home");
        } else {
          setError(true);
          setTimeout(() => {
            setPin("");
            setFirstPin(null);
            setStep("create");
            setError(false);
          }, 1000);
        }
      }
    }
  }, [pin, step, firstPin, navigate]);

  return (
    <div className="pincode wrapper">
      <div>
        <h2 className="pincode__title">
          {
            {
              create: t("pincode.createTitle"),
              confirm: t("pincode.confirmTitle"),
              enter: t("pincode.enterTitle"),
            }[step]
          }
        </h2>

        <div className="pincode__circles">
          {[0, 1, 2, 3].map((i) => (
            <span
              key={i}
              className={`pincode__circle ${
                i < pin.length ? (error ? "error" : "filled") : ""
              }`}
            />
          ))}
        </div>
      </div>

      <div className="pincode__keyboards">
        {[
          ["1", "2", "3"],
          ["4", "5", "6"],
          ["7", "8", "9"],
          ["", "0", "del"],
        ].map((row, idx) => (
          <div className="pincode__keyboard__row" key={idx}>
            {row.map((val) =>
              val === "del" ? (
                <button
                  key="del"
                  className="pincode__keyboard__key"
                  onClick={handleDelete}
                >
                  <FiDelete />
                </button>
              ) : val === "" ? (
                <button
                  key="empty"
                  className="pincode__keyboard__key"
                  style={{ opacity: 0, pointerEvents: "none" }}
                >
                  .
                </button>
              ) : (
                <button
                  key={val}
                  className="pincode__keyboard__key"
                  onClick={() => handleDigit(val)}
                >
                  {val}
                </button>
              )
            )}
          </div>
        ))}
      </div>
    </div>
  );
};

export default Pincode;
