import React, { createContext, useContext, useReducer, useEffect } from 'react';
import { readDirectoryTree, readMarkdownFile } from '../utils/fileUtils';

// 初始状态
const initialState = {
  directoryTree: [],
  currentFile: null,
  currentContent: '',
  isLoading: false,
  error: null,
  sidebarOpen: true
};

// Action 类型
export const ACTIONS = {
  SET_DIRECTORY_TREE: 'SET_DIRECTORY_TREE',
  SET_CURRENT_FILE: 'SET_CURRENT_FILE',
  SET_CURRENT_CONTENT: 'SET_CURRENT_CONTENT',
  SET_LOADING: 'SET_LOADING',
  SET_ERROR: 'SET_ERROR',
  TOGGLE_SIDEBAR: 'TOGGLE_SIDEBAR',
  TOGGLE_NODE_EXPANSION: 'TOGGLE_NODE_EXPANSION'
};

// Reducer 函数
function appReducer(state, action) {
  switch (action.type) {
    case ACTIONS.SET_DIRECTORY_TREE:
      return {
        ...state,
        directoryTree: action.payload,
        isLoading: false
      };
    
    case ACTIONS.SET_CURRENT_FILE:
      return {
        ...state,
        currentFile: action.payload
      };
    
    case ACTIONS.SET_CURRENT_CONTENT:
      return {
        ...state,
        currentContent: action.payload,
        isLoading: false
      };
    
    case ACTIONS.SET_LOADING:
      return {
        ...state,
        isLoading: action.payload
      };
    
    case ACTIONS.SET_ERROR:
      return {
        ...state,
        error: action.payload,
        isLoading: false
      };
    
    case ACTIONS.TOGGLE_SIDEBAR:
      return {
        ...state,
        sidebarOpen: !state.sidebarOpen
      };
    
    case ACTIONS.TOGGLE_NODE_EXPANSION:
      return {
        ...state,
        directoryTree: toggleNodeExpansion(state.directoryTree, action.payload)
      };
    
    default:
      return state;
  }
}

// 切换节点展开状态的辅助函数
function toggleNodeExpansion(nodes, targetPath) {
  return nodes.map(node => {
    if (node.path === targetPath) {
      return { ...node, isExpanded: !node.isExpanded };
    }
    if (node.children && node.children.length > 0) {
      return {
        ...node,
        children: toggleNodeExpansion(node.children, targetPath)
      };
    }
    return node;
  });
}

// 创建 Context
const AppContext = createContext();

// Context Provider 组件
export function AppProvider({ children }) {
  const [state, dispatch] = useReducer(appReducer, initialState);

  // 加载目录树
  const loadDirectoryTree = async () => {
    try {
      dispatch({ type: ACTIONS.SET_LOADING, payload: true });
      const tree = await readDirectoryTree();
      dispatch({ type: ACTIONS.SET_DIRECTORY_TREE, payload: tree });
    } catch (error) {
      dispatch({ type: ACTIONS.SET_ERROR, payload: error.message });
    }
  };

  // 选择文件
  const selectFile = async (filePath) => {
    try {
      dispatch({ type: ACTIONS.SET_LOADING, payload: true });
      dispatch({ type: ACTIONS.SET_CURRENT_FILE, payload: filePath });
      
      // 读取文件内容
      const content = await readMarkdownFile(filePath);
      dispatch({ type: ACTIONS.SET_CURRENT_CONTENT, payload: content });
    } catch (error) {
      dispatch({ type: ACTIONS.SET_ERROR, payload: error.message });
    }
  };

  // 切换侧边栏
  const toggleSidebar = () => {
    dispatch({ type: ACTIONS.TOGGLE_SIDEBAR });
  };

  // 切换节点展开状态
  const toggleNodeExpansion = (nodePath) => {
    dispatch({ type: ACTIONS.TOGGLE_NODE_EXPANSION, payload: nodePath });
  };

  // 初始化时加载目录树
  useEffect(() => {
    loadDirectoryTree();
  }, []);

  const value = {
    ...state,
    loadDirectoryTree,
    selectFile,
    toggleSidebar,
    toggleNodeExpansion
  };

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

// 自定义 Hook
export function useApp() {
  const context = useContext(AppContext);
  if (!context) {
    throw new Error('useApp must be used within an AppProvider');
  }
  return context;
}