import React, { useState, useEffect } from 'react';

export default function FolderTree() {
  const [folders, setFolders] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [expandedIds, setExpandedIds] = useState<Set<string>>(new Set());

  useEffect(() => {
    loadFolders();
  }, []);

  const loadFolders = async () => {
    setLoading(true);
    try {
      const result = await window.mcp.callTool('wrike_list_folders', {});
      setFolders(result.folders || []);
    } catch (error) {
      console.error('Failed to load folders:', error);
    } finally {
      setLoading(false);
    }
  };

  const toggleExpand = (id: string) => {
    const newExpanded = new Set(expandedIds);
    if (newExpanded.has(id)) {
      newExpanded.delete(id);
    } else {
      newExpanded.add(id);
    }
    setExpandedIds(newExpanded);
  };

  const buildTree = (parentId: string | null = null, level = 0) => {
    return folders
      .filter(f => parentId ? f.parentIds?.includes(parentId) : !f.parentIds?.length)
      .map(folder => (
        <div key={folder.id} style={{ marginLeft: level * 20 }}>
          <div
            style={{
              padding: '8px 12px',
              background: '#1f2937',
              borderRadius: '6px',
              marginBottom: '4px',
              cursor: 'pointer',
              display: 'flex',
              alignItems: 'center',
              gap: '8px',
            }}
            onClick={() => toggleExpand(folder.id)}
          >
            <span>{expandedIds.has(folder.id) ? '▼' : '▶'}</span>
            <span>{folder.title}</span>
            {folder.project && <span style={{ fontSize: '12px', color: '#3b82f6' }}>[Project]</span>}
          </div>
          {expandedIds.has(folder.id) && buildTree(folder.id, level + 1)}
        </div>
      ));
  };

  return (
    <div style={{ background: '#111827', color: '#f3f4f6', minHeight: '100vh', padding: '24px' }}>
      <h1 style={{ fontSize: '24px', fontWeight: 'bold', marginBottom: '24px' }}>Folder Tree</h1>
      
      <button
        onClick={loadFolders}
        style={{
          background: '#3b82f6',
          color: 'white',
          padding: '8px 16px',
          borderRadius: '6px',
          border: 'none',
          cursor: 'pointer',
          marginBottom: '24px',
        }}
      >
        Refresh
      </button>

      {loading ? <div>Loading...</div> : buildTree()}
    </div>
  );
}
