import React, { createContext, useContext, useState } from 'react';

// Define the shape of our context
interface DashboardContextType {
  activePage: string;
  setActivePage: (page: string) => void;
  isTransitioning: boolean;
  setIsTransitioning: (isTransitioning: boolean) => void;
  backToHome: () => void;
  navigateTo: (page: string) => void;
  transitionDirection: 'in' | 'out';
  setTransitionDirection: (direction: 'in' | 'out') => void;
}

// Create the context with default values
const DashboardContext = createContext<DashboardContextType>({
  activePage: 'home',
  setActivePage: () => {},
  isTransitioning: false,
  setIsTransitioning: () => {},
  backToHome: () => {},
  navigateTo: () => {},
  transitionDirection: 'in',
  setTransitionDirection: () => {},
});

// Custom hook for using the dashboard context
// export const useDashboard = () => useContext(DashboardContext);
// 确保DashboardProvider正确传递状态
export const useDashboard = () => {
  const context = useContext(DashboardContext);
  if (!context) {
    throw new Error('useDashboard必须在DashboardProvider内使用');
  }
  return context;
}

// Provider component
export const DashboardProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [activePage, setActivePage] = useState<string>('home');
  const [isTransitioning, setIsTransitioning] = useState<boolean>(false);
  const [transitionDirection, setTransitionDirection] = useState<'in' | 'out'>('in');

  // 切换到指定页面
  const navigateTo = (page: string) => {
    if (page === activePage) return;
    
    // 从主页切换到子页面
    if (activePage === 'home') {
      setTransitionDirection('in');
      setIsTransitioning(true);
      setTimeout(() => {
        setActivePage(page);
        setTimeout(() => {
          setIsTransitioning(false);
        }, 500);
      }, 500);
    } 
    // 在子页面之间切换
    else if (page !== 'home') {
      setTransitionDirection('out');
      setIsTransitioning(true);
      setTimeout(() => {
        setActivePage(page);
        setTransitionDirection('in');
        setTimeout(() => {
          setIsTransitioning(false);
        }, 500);
      }, 500);
    }
  };

  // 返回首页的方法
  const backToHome = () => {
    setTransitionDirection('out');
    setIsTransitioning(true);
    setTimeout(() => {
      setActivePage('home');
      setTimeout(() => {
        setIsTransitioning(false);
      }, 500);
    }, 500);
  };

  const contextValue = {
    activePage,
    setActivePage,
    isTransitioning,
    setIsTransitioning,
    backToHome,
    navigateTo,
    transitionDirection,
    setTransitionDirection,
  };

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

export default DashboardContext; 