import { useMemo, useEffect, useState } from 'react';
import { Tour, Grid } from 'antd';
import { useLocation } from 'react-router-dom';
import { useTourStore } from '../../stores/tour.store';
import { useAuthStore } from '../../stores/auth.store';
import { useSettingsStore } from '../../stores/settings.store';
import { tourRegistry } from './tourRegistry';
import type { TourStepContext } from './types';

/**
 * Layout-level tour runner.
 * Handles sections with route=null (e.g., getting-started) that target
 * AppLayout elements (sidebar, header, user menu).
 *
 * Page-specific tours are handled by <PageTour> on each page.
 */
export function AdminTour() {
  const { sections, activeSectionId, activeStep, launchSection, setStep, completeActiveSection, pauseActiveSection } = useTourStore();
  const { user } = useAuthStore();
  const settings = useSettingsStore((s) => s.settings);
  const location = useLocation();
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;
  const [open, setOpen] = useState(false);

  // Find the active layout-level section (route === null)
  const activeSection = useMemo(() => {
    if (!activeSectionId) return null;
    const section = tourRegistry.find((s) => s.id === activeSectionId);
    return section?.route === null ? section : null;
  }, [activeSectionId]);

  // Build steps for the active layout-level section
  const ctx: TourStepContext | null = useMemo(
    () => settings ? { settings, isMobile } : null,
    [settings, isMobile]
  );

  const steps = useMemo(
    () => (activeSection && ctx ? activeSection.buildSteps(ctx) : []),
    [activeSection, ctx]
  );

  // Open tour when a layout-level section is activated
  useEffect(() => {
    if (activeSection && steps.length > 0) {
      const timer = setTimeout(() => setOpen(true), 300);
      return () => clearTimeout(timer);
    }
    setOpen(false);
  }, [activeSection, steps.length]);

  // Auto-launch getting-started for new SUPER_ADMIN users on dashboard
  // Only auto-launch if the section has NEVER been started (not in sections map at all)
  useEffect(() => {
    const gettingStarted = sections['getting-started'];
    if (
      !gettingStarted &&
      !activeSectionId &&
      user?.role === 'SUPER_ADMIN' &&
      location.pathname === '/app' &&
      ctx
    ) {
      const gsDef = tourRegistry.find((s) => s.id === 'getting-started');
      if (gsDef) {
        const gsSteps = gsDef.buildSteps(ctx);
        if (gsSteps.length > 0) {
          const timer = setTimeout(() => launchSection('getting-started', gsSteps.length), 500);
          return () => clearTimeout(timer);
        }
      }
    }
  }, [sections, activeSectionId, user, location.pathname, ctx, launchSection]);

  if (!activeSection || steps.length === 0) return null;

  const isLastStep = activeStep >= steps.length - 1;

  return (
    <Tour
      open={open}
      current={activeStep}
      steps={steps}
      onChange={(step) => setStep(step)}
      onClose={() => {
        setOpen(false);
        if (isLastStep) {
          completeActiveSection();
        } else {
          pauseActiveSection();
        }
      }}
      onFinish={() => {
        setOpen(false);
        completeActiveSection();
      }}
    />
  );
}
