import React, { useState, useEffect, useRef } from "react";
import "./KeyboardShortcuts.styles.scss";
import { Keys } from "./Keycombo";
import { ReactComponent as CheckIcon } from "../../assets/checkbox-tick.svg";
import { Loader } from "../../components/Loader";
import { useShortcut } from "../../components/Shortcuts";
import { ShortcutManager } from "../../utils/shortcuts";
import { isMac } from "../../utils/shortcuts";

const tutorialSteps = [
  {
    text: "Open & Close Side Navigation by Pressing",
    firstSymbol: isMac ? "⌘" : null,
    firstText: isMac ? "command" : "Ctrl",
    secondText: "B",
    arrowPosition: "left-top",
  },
  {
    text: "Open Keyboard Settings by Pressing",
    firstSymbol: isMac ? "⌥" : null,
    firstText: isMac ? "option" : "Alt",
    secondText: "K",
    arrowPosition: "left",
  },
  {
    text: "Open Keyboard Shortcut Panel by Pressing",
    firstSymbol: isMac ? "⌘" : null,
    firstText: isMac ? "command" : "Ctrl",
    secondText: "K",
    arrowPosition: "top-right",
  },
];

const ProgressBar = ({ currentStep, totalSteps }) => {
  return (
    <div className="progress-bar">
      {Array.from({ length: totalSteps }, (_, index) => {
        const stepNum = index + 1;
        const isCompleted = index < currentStep;
        const isActive = index === currentStep;

        return (
          <React.Fragment key={index}>
            {index > 0 && (
              <div
                className={`progress-line ${
                  index <= currentStep ? "progress-line--active" : ""
                }`}
              />
            )}
            <div
              className={`progress-step ${
                isCompleted ? "progress-step--completed" : ""
              } ${isActive ? "progress-step--active" : ""}`}
            >
              {isCompleted ? (
                <CheckIcon />
              ) : (
                <span
                  className={
                    "step-number " + (isActive ? "step-number--active" : "")
                  }
                >
                  {stepNum}
                </span>
              )}
            </div>
          </React.Fragment>
        );
      })}
    </div>
  );
};

export const TutorialModal = ({
  setShowTutorialModal,
  onSkipClick,
}) => {
  const totalSteps = tutorialSteps.length;
  const [tutorialStep, setTutorialStep] = useState(0);
  const step = tutorialSteps[tutorialStep];
  const [showLottie, setShowLottie] = useState(false);
  const modalRef = useRef(null);
  const [step2Position, setStep2Position] = useState(null);

  useEffect(() => {
    if (tutorialStep === 2) {
      const button = document.getElementById("impact-header-keyboard-shortcuts-button");
      if (button && modalRef.current) {
        const btnRect = button.getBoundingClientRect();
        const modalWidth = modalRef.current.offsetWidth;
        const btnCenterX = btnRect.left + btnRect.width / 2;
        setStep2Position({
          top: btnRect.bottom + 17,
          left: btnCenterX - modalWidth / 2,
          arrowLeft: modalWidth / 2 - 10,
        });
      }
    }
  }, [tutorialStep]);

  const handleSkip = () => {
    setShowTutorialModal(false);
    onSkipClick?.();
  };

  useShortcut("mod+b", (e) => {
    ShortcutManager.getInstance().trigger('sidebar-toggle-mod-b', e);
    if (tutorialStep === 0) {
      setShowLottie(true);
    }
    setTimeout(() => {
      setTutorialStep(1);
      setShowLottie(false);
    }, 1000);
  }, {
    id: "tutorial-step-0-mod-b",
    priority: 2,
  });

  useShortcut(
    "alt+k",
    () => {
      if (tutorialStep === 1) {
        setShowLottie(true);
      }
      setTimeout(() => {
        setTutorialStep(2);
        setShowLottie(false);
      }, 1000);
    },
    {
      id: "tutorial-step-1-alt-k",
      priority: 2,
      propagate: true,
    }
  );

  useShortcut("mod+k", () => {
    if (tutorialStep === 2) {
      setShowLottie(true);
    }
    setTimeout(() => {
      setShowLottie(false);
      setShowTutorialModal(false);
    }, 1000);
  }, {
    id: "tutorial-step-2-mod-k",
    priority: 2,
    propagate: true,
  });

  return (
    <>
      <div
        ref={modalRef}
        className={`tutorial-modal-wrapper tutorial-modal--step-${tutorialStep} tutorial-modal--arrow-${step.arrowPosition}${
          document.querySelector('.impact-sidebar-container.sidebar-open')
            ? ' tutorial-modal--sidebar-expanded'
            : ''
        }`}
        style={
          tutorialStep === 2 && step2Position
            ? { top: step2Position.top, left: step2Position.left, transform: "none" }
            : undefined
        }
      >
        <div
          className={`tutorial-arrow tutorial-arrow--${step.arrowPosition}`}
          style={
            tutorialStep === 2 && step2Position
              ? { left: step2Position.arrowLeft, right: "auto" }
              : undefined
          }
        />
        <div className="top-section" role="button" tabIndex={0}>
          <div className="top-section-content">
            <span className="loader">
              {showLottie ? (
                <iframe
                  src="https://lottie.host/embed/bd7243cb-3821-46da-bbaa-56edfb4b2056/Z74goW01Yw.lottie"
                  className="lottie-iframe"
                />
              ) : (
                <Loader size="small" text="" />
              )}
            </span>
            <span className="top-section-text">{step.text}</span>
          </div>
          <div className="top-section-buttons">
            <Keys
              firstSymbol={step.firstSymbol}
              firstText={step.firstText}
              secondText={step.secondText}
            />
          </div>
        </div>

        <div className="bottom-section">
          <span
            className="bottom-section-text"
            onClick={handleSkip}
            role="button"
            tabIndex={0}
          >
            Skip
          </span>
          <div className="bottom-section-progress">
            <ProgressBar currentStep={tutorialStep} totalSteps={totalSteps} />
          </div>
        </div>
      </div>
    </>
  );
};
