import { useState, useEffect, useRef } from 'react';
import axios from 'axios';

// Tour IDs matching the backend constants
export const TOUR_IDS = {
  ZEITERFASSUNG_USERS: 'zeiterfassung_users',
  ZEITERFASSUNG_COMPANY_SETTINGS: 'zeiterfassung_company_settings',
  ZEITERFASSUNG_SHIFTS: 'zeiterfassung_shifts',
  ZEITERFASSUNG_TEMPLATES: 'zeiterfassung_templates',
  ZEITERFASSUNG_ROLES: 'zeiterfassung_roles',
  ZEITERFASSUNG_EDIT_SHIFT: 'zeiterfassung_edit_shift',
  ZEITERFASSUNG_CREATE_SHIFT: 'zeiterfassung_create_shift',
} as const;

type TourId = typeof TOUR_IDS[keyof typeof TOUR_IDS];

interface UseTourResult {
  runTour: boolean;
  setRunTour: (run: boolean) => void;
  tourStepIndex: number;
  setTourStepIndex: (index: number) => void;
  isTourCompleted: boolean;
  isLoading: boolean;
  markTourCompleted: () => Promise<void>;
  resetTour: () => Promise<void>;
}

/**
 * Custom hook to manage Joyride tours with database persistence
 *
 * @param tourId - Unique identifier for the tour
 * @param autoStart - Whether to automatically start the tour for first-time users
 * @param autoStartDelay - Delay in ms before auto-starting the tour
 * @returns Tour state and control functions
 */
export const useTour = (
  tourId: TourId,
  autoStart: boolean = true,
  autoStartDelay: number = 500
): UseTourResult => {
  const [runTour, setRunTour] = useState(false);
  const [tourStepIndex, setTourStepIndex] = useState(0);
  const [isTourCompleted, setIsTourCompleted] = useState(false);
  const [isLoading, setIsLoading] = useState(true);
  const autoStartTimeoutRef = useRef<NodeJS.Timeout | null>(null);

  // Load tour completion status from database
  useEffect(() => {
    const checkTourStatus = async () => {
      try {
        setIsLoading(true);
        const response = await axios.get(`/tours/${tourId}/is-completed`);
        const completed = response.data.completed;
        setIsTourCompleted(completed);
        setIsLoading(false);

        // Auto-start tour AFTER API response confirms not completed
        if (!completed && autoStart) {
          autoStartTimeoutRef.current = setTimeout(() => {
            setRunTour(true);
          }, autoStartDelay);
        }
      } catch (error) {
        console.error(`Error checking tour status for ${tourId}:`, error);
        setIsLoading(false);
      }
    };

    checkTourStatus();

    // Cleanup timeout on unmount or tourId change
    return () => {
      if (autoStartTimeoutRef.current) {
        clearTimeout(autoStartTimeoutRef.current);
        autoStartTimeoutRef.current = null;
      }
    };
  }, [tourId, autoStart, autoStartDelay]);

  // Mark tour as completed in database
  const markTourCompleted = async () => {
    try {
      await axios.post('/tours/complete', {
        tour_id: tourId,
      });
      setIsTourCompleted(true);
      setRunTour(false);
      setTourStepIndex(0);
    } catch (error) {
      console.error(`Error marking tour ${tourId} as completed:`, error);
    }
  };

  // Reset tour (mark as not completed) in database
  const resetTour = async () => {
    try {
      await axios.post('/tours/reset', {
        tour_id: tourId,
      });
      setIsTourCompleted(false);
      setTourStepIndex(0);
    } catch (error) {
      console.error(`Error resetting tour ${tourId}:`, error);
    }
  };

  return {
    runTour,
    setRunTour,
    tourStepIndex,
    setTourStepIndex,
    isTourCompleted,
    isLoading,
    markTourCompleted,
    resetTour,
  };
};
