import { useState, useEffect } from 'react';
import { invoke } from '@tauri-apps/api/tauri';

interface FileItem {
  name: string;
  path: string;
  is_dir: boolean;
}

const FileBrowser = ({ path }: { path: string }) => {
  const [files, setFiles] = useState<FileItem[]>([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    const loadFiles = async () => {
      setLoading(true);
      try {
        const result = await invoke<FileItem[]>('list_files', { path });
        setFiles(result);
      } catch (error) {
        console.error('Error listing files:', error);
      } finally {
        setLoading(false);
      }
    };
    loadFiles();
  }, [path]);

  return (
    <div className="flex-1 p-4">
      <h3 className="text-lg font-semibold mb-4">File Browser: {path || 'Root'}</h3>
      {loading ? (
        <p>Loading...</p>
      ) : (
        <ul className="space-y-1">
          {files.map((file) => (
            <li key={file.path} className="p-2 hover:bg-gray-100 rounded">
              {file.is_dir ? '📁' : '📄'} {file.name}
            </li>
          ))}
        </ul>
      )}
    </div>
  );
};

export default FileBrowser;
