import { invoke } from '@tauri-apps/api/tauri';
import { open } from '@tauri-apps/api/dialog';
import { writeBinaryFile, BaseDirectory } from '@tauri-apps/api/fs';
import { useState } from 'react';

interface FileOperationsProps {
  currentPath: string;
  onRefresh: () => void;
}

const FileOperations = ({ currentPath, onRefresh }: FileOperationsProps) => {
  const [uploadProgress, setUploadProgress] = useState(0);

  const handleUpload = async () => {
    try {
      const selected = await open({
        multiple: false,
        directory: false,
      });
      
      if (selected) {
        const filePath = Array.isArray(selected) ? selected[0] : selected;
        await invoke('upload_file', { 
          srcPath: filePath, 
          destPath: currentPath,
          onProgress: (progress: number) => setUploadProgress(progress)
        });
        onRefresh();
        alert('File uploaded successfully!');
      }
    } catch (error) {
      console.error('Upload failed:', error);
      alert('Upload failed!');
    } finally {
      setUploadProgress(0);
    }
  };

  const createFolder = async () => {
    const folderName = prompt('Enter folder name:');
    if (folderName) {
      try {
        await invoke('create_folder', { 
          path: currentPath, 
          name: folderName 
        });
        onRefresh();
      } catch (error) {
        console.error('Error creating folder:', error);
        alert('Failed to create folder');
      }
    }
  };

  return (
    <div className="p-4 border-t border-gray-300 space-y-3">
      <h3 className="text-lg font-semibold">File Operations</h3>
      <div className="flex space-x-2">
        <button
          onClick={handleUpload}
          className="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600"
        >
          Upload
        </button>
        <button
          onClick={createFolder}
          className="bg-green-500 text-white px-4 py-2 rounded hover:bg-green-600"
        >
          New Folder
        </button>
      </div>
      {uploadProgress > 0 && (
        <div className="w-full bg-gray-200 rounded-full h-2.5">
          <div 
            className="bg-blue-600 h-2.5 rounded-full" 
            style={{ width: `${uploadProgress}%` }}
          ></div>
        </div>
      )}
    </div>
  );
};

export default FileOperations;
