import { createContext, useContext, useState, useEffect, useCallback, ReactNode } from "react";
import { useAuth } from "@/hooks/useAuth";

interface OnboardingStep {
  id: string;
  title: string;
  description: string;
  target: string;
  content: ReactNode;
  action?: string;
  position?: "top" | "bottom" | "left" | "right";
  optional?: boolean;
}

interface OnboardingContextType {
  isActive: boolean;
  currentStep: number;
  steps: OnboardingStep[];
  startOnboarding: (tourType: string) => void;
  nextStep: () => void;
  prevStep: () => void;
  skipStep: () => void;
  endOnboarding: () => void;
  isStepCompleted: (stepId: string) => boolean;
  markStepCompleted: (stepId: string) => void;
  completedSteps: string[];
}

const OnboardingContext = createContext<OnboardingContextType | undefined>(undefined);

export function useOnboarding() {
  const context = useContext(OnboardingContext);
  if (context === undefined) {
    throw new Error("useOnboarding must be used within an OnboardingProvider");
  }
  return context;
}

export const ONBOARDING_TOURS = {
  dashboard: [
    {
      id: "welcome",
      title: "Welcome to SportsPro!",
      description: "Let's take a quick tour to help you get started with managing your sports organization.",
      target: "[data-tour='welcome']",
      content: "This dashboard is your central hub for managing teams, players, and club activities.",
      position: "bottom" as const,
    },
    {
      id: "navigation",
      title: "Main Navigation",
      description: "Use the sidebar to navigate between different sections of the platform.",
      target: "[data-tour='sidebar']",
      content: "Teams, Players, Attendance, and other key features are accessible from here.",
      position: "right" as const,
    },
    {
      id: "teams-overview",
      title: "Teams Section",
      description: "Manage your teams, view rosters, and track performance.",
      target: "[data-tour='teams-card']",
      content: "Click here to view and manage all your teams.",
      action: "Click to explore teams",
      position: "top" as const,
    },
  ],
  teamManagement: [
    {
      id: "team-navigation",
      title: "Team Management",
      description: "Navigate to the teams section to manage your organization's teams.",
      target: "[data-tour='sidebar']",
      content: "Click 'Teams' in the sidebar to view and manage all teams.",
      action: "Navigate to Teams",
      position: "right" as const,
    },
  ],
  playerRegistration: [
    {
      id: "player-navigation",
      title: "Player Management",
      description: "Navigate to the players section to register and manage players.",
      target: "[data-tour='sidebar']",
      content: "Click 'Players' in the sidebar to access player management features.",
      action: "Navigate to Players",
      position: "right" as const,
    },
  ],
  settingsTour: [
    {
      id: "settings-welcome",
      title: "Personalize Your Experience",
      description: "Customize SportsPro to match your preferences.",
      target: "[data-tour='settings-header']",
      content: "Settings allow you to customize the platform to your needs.",
      position: "bottom" as const,
    },
    {
      id: "settings-profile",
      title: "Profile Settings",
      description: "Update your personal information and account details.",
      target: "[data-tour='settings-profile-tab']",
      content: "Keep your profile information up to date for better collaboration.",
      position: "bottom" as const,
    },
    {
      id: "settings-appearance",
      title: "Appearance & Theme",
      description: "Choose your preferred theme and customize the interface.",
      target: "[data-tour='settings-appearance-tab']",
      content: "Switch between light, dark, or system theme preferences.",
      position: "bottom" as const,
    },
    {
      id: "settings-notifications",
      title: "Notification Preferences",
      description: "Control how you receive updates and alerts.",
      target: "[data-tour='settings-notifications-tab']",
      content: "Manage email, push, and in-app notification settings.",
      position: "bottom" as const,
    },
  ],
  reportsTour: [
    {
      id: "reports-navigation",
      title: "Reports & Analytics",
      description: "Access comprehensive reports and analytics for your organization.",
      target: "[data-tour='sidebar']",
      content: "Click 'Reports' in the sidebar to view fixtures, attendance, revenue, and performance data.",
      action: "Navigate to Reports",
      position: "right" as const,
    },
  ],
  adminTour: [
    {
      id: "admin-navigation",
      title: "Admin Panel",
      description: "Access administrative functions for your organization.",
      target: "[data-tour='sidebar']",
      content: "Use the sidebar to navigate to User Management, Branding, Security, and other admin sections.",
      action: "Explore Admin Features",
      position: "right" as const,
    },
  ],
};

interface OnboardingProviderProps {
  children: ReactNode;
}

export function OnboardingProvider({ children }: OnboardingProviderProps) {
  const { user } = useAuth();
  const [isActive, setIsActive] = useState(false);
  const [currentStep, setCurrentStep] = useState(0);
  const [steps, setSteps] = useState<OnboardingStep[]>([]);
  const [completedSteps, setCompletedSteps] = useState<string[]>([]);

  // Load completed steps from localStorage
  useEffect(() => {
    if (user) {
      const saved = localStorage.getItem(`onboarding-completed-${user.id}`);
      if (saved) {
        setCompletedSteps(JSON.parse(saved));
      }
    }
  }, [user]);

  const startOnboarding = useCallback((tourType: string) => {
    const tourSteps = ONBOARDING_TOURS[tourType as keyof typeof ONBOARDING_TOURS];
    if (tourSteps) {
      setSteps(tourSteps);
      setCurrentStep(0);
      setIsActive(true);
    }
  }, []);

  // Check if user needs onboarding
  useEffect(() => {
    if (user && completedSteps.length === 0) {
      const hasSeenOnboarding = localStorage.getItem(`onboarding-seen-${user.id}`);
      if (!hasSeenOnboarding) {
        // Auto-start dashboard tour for new users
        setTimeout(() => {
          startOnboarding('dashboard');
        }, 1000);
      }
    }
  }, [user, completedSteps, startOnboarding]);

  const nextStep = () => {
    if (currentStep < steps.length - 1) {
      setCurrentStep(currentStep + 1);
    } else {
      endOnboarding();
    }
  };

  const prevStep = () => {
    if (currentStep > 0) {
      setCurrentStep(currentStep - 1);
    }
  };

  const skipStep = () => {
    nextStep();
  };

  const endOnboarding = () => {
    setIsActive(false);
    setCurrentStep(0);
    setSteps([]);
    
    if (user) {
      localStorage.setItem(`onboarding-seen-${user.id}`, 'true');
    }
  };

  const isStepCompleted = (stepId: string) => {
    return completedSteps.includes(stepId);
  };

  const markStepCompleted = (stepId: string) => {
    if (!completedSteps.includes(stepId)) {
      const newCompleted = [...completedSteps, stepId];
      setCompletedSteps(newCompleted);
      
      if (user) {
        localStorage.setItem(`onboarding-completed-${user.id}`, JSON.stringify(newCompleted));
      }
    }
  };

  const value: OnboardingContextType = {
    isActive,
    currentStep,
    steps,
    startOnboarding,
    nextStep,
    prevStep,
    skipStep,
    endOnboarding,
    isStepCompleted,
    markStepCompleted,
    completedSteps,
  };

  return (
    <OnboardingContext.Provider value={value}>
      {children}
    </OnboardingContext.Provider>
  );
}