import React, { useEffect } from 'react';
import { useApp } from '../context/AppContext';
import { NODE_TYPES } from '../utils/fileUtils';
import './Sidebar.css';

function TreeNode({ node, level = 0 }) {
  const { selectFile, toggleNodeExpansion, currentFile } = useApp();

  const handleClick = () => {
    if (node.type === NODE_TYPES.FOLDER) {
      toggleNodeExpansion(node.path);
    } else {
      selectFile(node.path);
    }
  };

  const isSelected = currentFile === node.path;
  const hasChildren = node.children && node.children.length > 0;

  return (
    <div className="tree-node">
      <div
        className={	ree-node-content }
        style={{ paddingLeft: ${level * 18 + 14}px }}
        onClick={handleClick}
        role="button"
        tabIndex={0}
        onKeyDown={(event) => {
          if (event.key === 'Enter' || event.key === ' ') {
            event.preventDefault();
            handleClick();
          }
        }}
      >
        {node.type === NODE_TYPES.FOLDER && (
          <span className={	ree-node-icon } aria-hidden>
            {hasChildren ? (node.isExpanded ? '📂' : '📁') : '📁'}
          </span>
        )}
        {node.type === NODE_TYPES.FILE && (
          <span className="tree-node-icon" aria-hidden>📄</span>
        )}
        <span className="tree-node-name">{node.name}</span>
      </div>

      {node.type === NODE_TYPES.FOLDER && node.isExpanded && hasChildren && (
        <div className="tree-node-children">
          {node.children.map((child) => (
            <TreeNode key={child.path} node={child} level={level + 1} />
          ))}
        </div>
      )}
    </div>
  );
}

export default function Sidebar() {
  const { directoryTree, isLoading, error, sidebarOpen, toggleSidebar } = useApp();

  const toggleLabel = sidebarOpen ? '收起目录' : '展开目录';

  useEffect(() => {
    if (typeof window === 'undefined') {
      return () => undefined;
    }

    const handleScrollLock = () => {
      const shouldLock = sidebarOpen && window.innerWidth <= 1024;
      document.body.classList.toggle('no-scroll', shouldLock);
    };

    handleScrollLock();
    window.addEventListener('resize', handleScrollLock);

    return () => {
      window.removeEventListener('resize', handleScrollLock);
      document.body.classList.remove('no-scroll');
    };
  }, [sidebarOpen]);

  return (
    <>
      <aside className={sidebar } aria-hidden={!sidebarOpen}>
        <div className="sidebar-header">
          <h2>📚 萌芽笔记</h2>
          <button type="button" onClick={toggleSidebar} className="toggle-button" aria-label={toggleLabel}>
            ✕
          </button>
        </div>

        <div className="sidebar-content">
          {isLoading && (
            <div className="loading">
              <div className="loading-spinner" aria-hidden />
              <span>加载中...</span>
            </div>
          )}

          {error && (
            <div className="error">
              <span>目录加载失败: {error}</span>
            </div>
          )}

          {!isLoading && !error && (
            <div className="directory-tree">
              {directoryTree.map((node) => (
                <TreeNode key={node.path} node={node} />
              ))}
            </div>
          )}
        </div>
      </aside>

      <div
        className={sidebar-backdrop }
        onClick={sidebarOpen ? toggleSidebar : undefined}
        aria-hidden="true"
      />

      <div className="sidebar-toggle">
        <button
          type="button"
          onClick={toggleSidebar}
          className={	oggle-button }
          aria-label={toggleLabel}
        >
          {sidebarOpen ? '✕' : '☰'}
        </button>
      </div>
    </>
  );
}
