import { useEffect, useState } from 'react';
import { listDirectory } from '@/lib/tauri-bridge';
import { isPlaceholderRoot } from '@/lib/workspace-path';
import type { DirEntry } from '@/types/workbench';
import { useActiveWorkspace } from '@/features/workspace/WorkspaceStore';

export function FileTree() {
  const workspace = useActiveWorkspace();
  const [entries, setEntries] = useState<DirEntry[]>([]);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (!workspace?.rootPath || isPlaceholderRoot(workspace.rootPath)) {
      setEntries([]);
      return;
    }
    let cancelled = false;
    setLoading(true);
    setError(null);
    void listDirectory(workspace.rootPath, 120)
      .then((items) => {
        if (!cancelled) setEntries(items);
      })
      .catch((err: unknown) => {
        if (!cancelled) {
          setError(err instanceof Error ? err.message : String(err));
          setEntries([]);
        }
      })
      .finally(() => {
        if (!cancelled) setLoading(false);
      });
    return () => {
      cancelled = true;
    };
  }, [workspace?.rootPath, workspace?.updatedAt]);

  if (!workspace || isPlaceholderRoot(workspace.rootPath)) return null;

  return (
    <section className="file-tree">
      <div className="file-tree__header">Project files</div>
      <div className="file-tree__path">{workspace.rootPath}</div>
      {loading && <div className="file-tree__hint">Loading…</div>}
      {error && <div className="file-tree__error">{error}</div>}
      <ul className="file-tree__list">
        {entries.map((entry) => (
          <li key={entry.path} className={entry.isDir ? 'is-dir' : 'is-file'}>
            <span className="file-tree__icon">{entry.isDir ? '📁' : '📄'}</span>
            <span className="file-tree__name">{entry.name}</span>
          </li>
        ))}
      </ul>
    </section>
  );
}
