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

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

interface FileBrowserProps {
  path: string;
  onFileSelect?: (path: string) => void;
}

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

  useEffect(() => {
    const loadFiles = async () => {
      setLoading(true);
      try {
        const result = await core.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 cursor-pointer ${file.is_dir ? 'font-medium' : ''}`}
              onClick={() => onFileSelect && onFileSelect(file.path)}
            >
              {file.is_dir ? '📁' : '📄'} {file.name}
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}
