import React, { useEffect, useState } from 'react';
import { api } from '../../services/api';

export default function FileExplorer({ onSelectFile, activeFile }) {
  const [files, setFiles] = useState([]);
  const [loading, setLoading] = useState(true);

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

  const loadFiles = async () => {
    setLoading(true);
    try {
      const data = await api.getFiles();
      setFiles(Array.isArray(data) ? data : []);
    } catch (err) {
      console.error("Failed to load workspace files:", err);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="w-64 bg-slate-900 text-slate-300 border-r border-slate-800 flex flex-col h-full select-none">
      <div className="p-3 border-b border-slate-800 font-semibold text-xs uppercase tracking-wider text-slate-400 flex justify-between items-center">
        <span>Explorer</span>
        <button onClick={loadFiles} className="hover:text-white transition-colors">🔄</button>
      </div>

      <div className="flex-1 overflow-y-auto p-2 text-sm">
        {loading ? (
          <div className="p-3 text-slate-500 text-xs">Loading tree...</div>
        ) : files.length === 0 ? (
          <div className="p-3 text-slate-500 text-xs">No files found.</div>
        ) : (
          files.map((file) => (
            <div
              key={file.path || file.name}
              onClick={() => onSelectFile(file.path || file.name)}
              className={`px-3 py-1.5 rounded cursor-pointer flex items-center gap-2 transition-colors ${
                activeFile === (file.path || file.name)
                  ? 'bg-blue-600 text-white font-medium'
                  : 'hover:bg-slate-800 text-slate-300'
              }`}
            >
              <span>{file.is_dir ? '📁' : '📄'}</span>
              <span className="truncate">{file.name || file.path}</span>
            </div>
          ))
        )}
      </div>
    </div>
  );
}
