import { useState, useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import type { EventData, Step } from 'react-joyride';

const STORAGE_KEY = 'tutorial_completed';
const JOYRIDE_ACTION_CLOSE = 'close';
const JOYRIDE_EVENT_STEP_AFTER = 'step:after';
const JOYRIDE_STATUS_FINISHED = 'finished';
const JOYRIDE_STATUS_SKIPPED = 'skipped';

export function useTutorial(initialLoading: boolean, isMobile: boolean, blocked = false) {
  const { t } = useTranslation();

  const steps: Step[] = useMemo(
    () => [
      {
        target: '[data-tutorial="filters"]',
        title: t('tutorial.step1Title'),
        content: t('tutorial.step1Content'),
        placement: 'right' as const,
        skipBeacon: true,
      },
      {
        target: '[data-tutorial="ai-filters"]',
        title: t('tutorial.step2Title'),
        content: t('tutorial.step2Content'),
        placement: 'right' as const,
        skipBeacon: true,
      },
      {
        target: '[data-tutorial="map"]',
        title: t('tutorial.step3Title'),
        content: t('tutorial.step3Content'),
        // The map fills the viewport; directional placements push the tooltip
        // off-screen. Center it over the map instead.
        placement: 'center' as const,
        skipBeacon: true,
      },
      {
        target: '[data-tutorial="search"]',
        title: t('tutorial.step4Title'),
        content: t('tutorial.step4Content'),
        placement: 'bottom' as const,
        skipBeacon: true,
      },
      {
        target: '[data-tutorial="poi-button"]',
        title: t('tutorial.step6Title'),
        content: t('tutorial.step6Content'),
        placement: 'left' as const,
        skipBeacon: true,
      },
    ],
    [t]
  );

  const [run, setRun] = useState(() => {
    if (isMobile) return false;
    return !localStorage.getItem(STORAGE_KEY);
  });

  const shouldRun = run && !initialLoading && !isMobile && !blocked;

  const handleCallback = useCallback((data: EventData) => {
    const { status, action, type } = data;

    if (status === JOYRIDE_STATUS_FINISHED || status === JOYRIDE_STATUS_SKIPPED) {
      localStorage.setItem(STORAGE_KEY, '1');
      setRun(false);
    }
    // Also stop if user closes a tooltip via the X button
    if (action === JOYRIDE_ACTION_CLOSE && type === JOYRIDE_EVENT_STEP_AFTER) {
      localStorage.setItem(STORAGE_KEY, '1');
      setRun(false);
    }
  }, []);

  const resetTutorial = useCallback(() => {
    localStorage.removeItem(STORAGE_KEY);
    setRun(true);
  }, []);

  return useMemo(
    () => ({
      steps,
      run: shouldRun,
      handleCallback,
      resetTutorial,
    }),
    [steps, shouldRun, handleCallback, resetTutorial]
  );
}
