import { useCallback, useEffect, useRef, useState, type JSX } from "react";
import { useConfigStore } from "../../stores/config-store";
import { Tabs } from "../../../shared/tabs";
import { useOnboardingStore, type OnboardingStep } from "./use-onboarding-store";
import { useT } from "../../i18n-context";
import { WelcomeStep } from "./steps/WelcomeStep";
import { ModelDownloadStep } from "./steps/ModelDownloadStep";
import { PermissionsStep } from "./steps/PermissionsStep";
import { ShortcutLearnStep } from "./steps/ShortcutLearnStep";
import { TryItStep } from "./steps/TryItStep";
import { HudDemoStep } from "./steps/HudDemoStep";
import { LlmIntroStep } from "./steps/LlmIntroStep";
import { LaunchAtLoginStep } from "./steps/LaunchAtLoginStep";
import { DoneStep } from "./steps/DoneStep";
import { XIcon } from "../../../shared/icons";
import styles from "./OnboardingOverlay.module.scss";

const TOTAL_STEPS = 9;
const CLOSE_ANIMATION_MS = 500;

export function OnboardingOverlay() {
  const t = useT();
  const step = useOnboardingStore((s) => s.step);
  const back = useOnboardingStore((s) => s.back);
  const reset = useOnboardingStore((s) => s.reset);
  const forceOpen = useOnboardingStore((s) => s.forceOpen);
  const setForceOpen = useOnboardingStore((s) => s.setForceOpen);
  const updateConfig = useConfigStore((s) => s.updateConfig);
  const saveConfig = useConfigStore((s) => s.saveConfig);
  const setActiveTab = useConfigStore((s) => s.setActiveTab);
  const [closing, setClosing] = useState(false);
  const closingRef = useRef(false);
  const trackedRef = useRef(false);

  useEffect(() => {
    if (trackedRef.current) return;
    trackedRef.current = true;
    window.voxApi.analytics.track("onboarding_started", {
      is_first_time: !forceOpen,
    });
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const completeOnboarding = useCallback(async () => {
    setForceOpen(false);
    updateConfig({ onboardingCompleted: true });
    await saveConfig(false);
    reset();
    window.voxApi.shortcuts.enable(true);
  }, [setForceOpen, updateConfig, saveConfig, reset]);

  const animateClose = useCallback(
    (afterClose: () => Promise<void> | void) => {
      if (closingRef.current) return;
      closingRef.current = true;
      setClosing(true);
      setTimeout(async () => {
        await completeOnboarding();
        document.querySelector(".content")?.scrollTo({ top: 0 });
        afterClose();
      }, CLOSE_ANIMATION_MS);
    },
    [completeOnboarding],
  );

  const handleSkip = useCallback(() => {
    const currentStep = useOnboardingStore.getState().step;
    animateClose(() => {
      window.voxApi.analytics.track("onboarding_skipped", { skipped_at_step: currentStep });
      setActiveTab(Tabs.GENERAL);
    });
  }, [animateClose, setActiveTab]);

  const handleComplete = useCallback(() => {
    animateClose(() => {
      window.voxApi.analytics.track("onboarding_completed", { completed_step: 8, skipped: false });
      setActiveTab(Tabs.TRANSCRIPTIONS);
    });
  }, [animateClose, setActiveTab]);

  const handleExploreSettings = useCallback(() => {
    animateClose(() => {
      window.voxApi.analytics.track("onboarding_completed", { completed_step: 8, skipped: false });
      setActiveTab(Tabs.GENERAL);
    });
  }, [animateClose, setActiveTab]);

  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === "Escape") {
        handleSkip();
      }
    };
    window.addEventListener("keydown", handleKeyDown);
    return () => window.removeEventListener("keydown", handleKeyDown);
  }, [handleSkip]);

  const SHORTCUT_LEARN_STEP = 3;
  useEffect(() => {
    if (step === SHORTCUT_LEARN_STEP) {
      window.voxApi.shortcuts.disable();
      localStorage.setItem("vox:shortcuts-banner-dismissed", "true");
    }
    return () => {
      if (step === SHORTCUT_LEARN_STEP) {
        window.voxApi.shortcuts.enable(true);
      }
    };
  }, [step]);

  const steps: Record<OnboardingStep, JSX.Element> = {
    0: <WelcomeStep />,
    1: <ModelDownloadStep />,
    2: <PermissionsStep />,
    3: <ShortcutLearnStep />,
    4: <TryItStep />,
    5: <HudDemoStep />,
    6: <LlmIntroStep />,
    7: <LaunchAtLoginStep />,
    8: <DoneStep onComplete={handleComplete} onExploreSettings={handleExploreSettings} />,
  };

  return (
    <div className={`${styles.overlay} ${closing ? styles.overlayClosing : ""}`}>
      <button className={styles.closeBtn} onClick={handleSkip} aria-label="Close" type="button">
        <XIcon width={18} height={18} />
      </button>
      <div className={styles.container}>
        {step > 0 && step < 8 && (
          <div className={styles.topNav}>
            <button className={styles.backBtn} onClick={back}>
              {t("onboarding.navigation.back")}
            </button>
            <button className={styles.skipBtn} onClick={handleSkip}>
              {t("onboarding.navigation.skip")}
            </button>
          </div>
        )}
        {step === 0 && (
          <div className={styles.topNav}>
            <span />
            <button className={styles.skipBtn} onClick={handleSkip}>
              {t("onboarding.navigation.skip")}
            </button>
          </div>
        )}

        <div className={styles.stepContainer}>
          {steps[step]}
        </div>

        <div className={styles.dots}>
          {Array.from({ length: TOTAL_STEPS }, (_, i) => (
            <span
              key={i}
              className={`${styles.dot} ${i === step ? styles.dotActive : ""} ${i < step ? styles.dotCompleted : ""}`}
            />
          ))}
        </div>
      </div>
    </div>
  );
}
