import React, { useState, useEffect, useRef, useCallback } from "react";
import "./KeyboardShortcuts.styles.scss";
import { ShortcutLandingPage } from "./ShortcutLandingPage";
import { Screen2 } from "./screen2";
import { Screen3 } from "./screen3";
import { Badge } from "../Badge";
import { Button } from "../Button";
import CloseRoundedIcon from "@mui/icons-material/CloseRounded";
import { TutorialModal } from "./tutorial";
import { AllSetBox } from "./allSetBox";

/** Duration (ms) each slide stays before auto-advancing */
const SLIDE_DURATIONS = [4500, 8000, 9000];
const TOTAL_SLIDES = SLIDE_DURATIONS.length;

export const KeyboardShortcuts = ({
  showLandingPage = true,
  showTutorial = false,
  showAllSetBox = false,
  onRemindMeLater = () => {},
  onClose = () => {},
  screen2VideoSrc,
  screen3VideoSrc,
  onSkipClick = () => {},
  onCloseAllSetBox = () => {},
}) => {
  const [activeIndex, setActiveIndex] = useState(0);
  const [leftLandingOnce, setLeftLandingOnce] = useState(false);
  const [showKeyboardShortcuts, setShowKeyboardShortcuts] = useState(true);
  const [direction, setDirection] = useState("forward");
  const [animKey, setAnimKey] = useState(0);
  const timerRef = useRef(null);
  const [showLandingPageScreen, setShowLandingPageScreen] =
    useState(showLandingPage);
  const [isSmallScreen, setIsSmallScreen] = useState(
    () => window.matchMedia("(max-width: 1512px)").matches
  );

  useEffect(() => {
    const mql = window.matchMedia("(max-width: 1512px)");
    const handler = (e) => setIsSmallScreen(e.matches);
    mql.addEventListener("change", handler);
    return () => mql.removeEventListener("change", handler);
  }, []);

  const goToSlide = useCallback((index, dir = "forward") => {
    setDirection(dir);
    setActiveIndex(index);
    setAnimKey((k) => k + 1);
    if (index !== 0) setLeftLandingOnce(true);
  }, []);

  useEffect(() => {
    clearTimeout(timerRef.current);
    timerRef.current = setTimeout(() => {
      goToSlide((activeIndex + 1) % TOTAL_SLIDES, "forward");
    }, SLIDE_DURATIONS[activeIndex]);
    return () => clearTimeout(timerRef.current);
  }, [activeIndex, goToSlide]);

  const playLandingEntrance = activeIndex === 0 && !leftLandingOnce;

  const [showTutorialModal, setShowTutorialModal] = useState(showTutorial);
  const screens = [
    <ShortcutLandingPage key="landing" playEntrance={playLandingEntrance} />,
    <Screen2 key="screen2" videoSrc={screen2VideoSrc} />,
    <Screen3 key="screen3" videoSrc={screen3VideoSrc} />,
  ];
  useEffect(() => {
    setShowTutorialModal(showTutorial);
  }, [showTutorial]);

  useEffect(() => {
    setShowLandingPageScreen(showLandingPage);
  }, [showLandingPage]);

  return (
    <>
      {showKeyboardShortcuts ? (
        <>
          {showLandingPageScreen && (
            <>
              <div
                aria-hidden="true"
                className="keyboard-shortcuts-overlay"
              ></div>
              <div className="keyboard-shortcuts-container-wrapper">
                <div
                  className="close-icon-container"
                  onClick={() => {
                    setShowKeyboardShortcuts(false);
                    onClose?.();
                  }}
                >
                  <CloseRoundedIcon
                    fontSize="small"
                    sx={{ color: "#60697D" }}
                  />
                </div>
                <div className="keyboard-shortcuts-container">
                  <div
                    className={`page-header${
                      playLandingEntrance
                        ? " shortcut-landing-entrance-header"
                        : ""
                    }`}
                  >
                    <Badge
                      label="New Feature"
                      variant="subtle"
                      color="info"
                      size={isSmallScreen ? "small" : "default"}
                    />
                    <div className="page-header-title-discription">
                      <span className="page-header-title">
                        Keyboard shortcuts
                      </span>
                      <span className="page-header-description">
                        Key Combos That Help You Work Faster Without a Mouse.
                      </span>
                    </div>
                  </div>

                  <div className="middle-section">
                    <div
                      key={animKey}
                      className={`screen-slide screen-slide--${direction}`}
                    >
                      {screens[activeIndex]}
                    </div>

                    <div className="button-carousel-wrapper">
                      {SLIDE_DURATIONS.map((duration, i) => (
                        <div
                          key={i}
                          className={`button ${
                            activeIndex === i ? "active" : ""
                          }`}
                          style={
                            activeIndex === i
                              ? { "--dot-duration": `${duration}ms` }
                              : {}
                          }
                          onClick={() => {
                            const dir =
                              i > activeIndex ? "forward" : "backward";
                            goToSlide(i, dir);
                          }}
                        />
                      ))}
                    </div>
                  </div>

                  <div
                    className={`page-footer${
                      playLandingEntrance
                        ? " shortcut-landing-entrance-footer"
                        : ""
                    }`}
                  >
                    <div className="page-footer-buttons">
                      <Button
                        variant="tertiary"
                        size={isSmallScreen ? "small" : "large"}
                        onClick={() => {
                          onRemindMeLater?.();
                          setShowKeyboardShortcuts(false);
                        }}
                      >
                        Remind Me Later
                      </Button>
                      <Button
                        size={isSmallScreen ? "small" : "large"}
                        onClick={() => {
                          setShowLandingPageScreen(false);
                          setShowTutorialModal(true);
                        }}
                      >
                        Try Now
                      </Button>
                    </div>
                  </div>
                </div>
              </div>
            </>
          )}

          {showTutorialModal && (
            <div aria-hidden="true" className="tutorial-overlay"></div>
          )}

          {showTutorialModal && (
            <TutorialModal
              setShowTutorialModal={setShowTutorialModal}
              onSkipClick={onSkipClick}
            />
          )}

          {showAllSetBox && (
            <AllSetBox onCloseAllSetBox={onCloseAllSetBox} />
          )}
        </>
      ) : null}
    </>
  );
};
