import React, { useState, useEffect } from 'react';
import { Filesystem, Directory, FileInfo } from '@capacitor/filesystem';
import { Folder, FileText, ChevronLeft, RefreshCw, AlertTriangle, HardDrive, Image as ImageIcon, Music, Video } from 'lucide-react';

interface NativeFileManagerProps {
  initialPath?: string;
}

export function NativeFileManager({ initialPath = '' }: NativeFileManagerProps) {
  const [currentPath, setCurrentPath] = useState(initialPath);
  const [files, setFiles] = useState<FileInfo[]>([]);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  // Load files when path changes
  useEffect(() => {
    loadFiles(currentPath);
  }, [currentPath]);

  const loadFiles = async (path: string) => {
    try {
      setLoading(true);
      setError(null);
      
      // Request permissions implicitly by trying to read
      // For Android 10+ strict scoping, we might default to Directory.Documents or External
      // But let's try reading the directory provided
      
      const result = await Filesystem.readdir({
        path: path,
        directory: Directory.External, // Use External storage (usually /storage/emulated/0)
      });

      // Sort: Folders first, then files
      const sortedFiles = result.files.sort((a, b) => {
        if (a.type === 'directory' && b.type !== 'directory') return -1;
        if (a.type !== 'directory' && b.type === 'directory') return 1;
        return a.name.localeCompare(b.name);
      });

      setFiles(sortedFiles);
    } catch (err: any) {
      console.error('File system error:', err);
      setError(err.message || 'Failed to access file system');
    } finally {
      setLoading(false);
    }
  };

  const handleFileClick = (file: FileInfo) => {
    if (file.type === 'directory') {
      setCurrentPath(currentPath ? `${currentPath}/${file.name}` : file.name);
    } else {
      // Handle file opening - for now just show info or use Capacitor Opener
      // We could add a simple viewer or toast
      console.log('Selected file:', file);
    }
  };

  const handleUpDir = () => {
    if (!currentPath) return;
    const parentPath = currentPath.split('/').slice(0, -1).join('/');
    setCurrentPath(parentPath);
  };

  const getFileIcon = (file: FileInfo) => {
    if (file.type === 'directory') return <Folder className="w-6 h-6 text-yellow-500" />;
    const ext = file.name.split('.').pop()?.toLowerCase();
    if (['jpg', 'jpeg', 'png', 'gif', 'webp'].includes(ext || '')) return <ImageIcon className="w-6 h-6 text-purple-400" />;
    if (['mp4', 'mov', 'avi'].includes(ext || '')) return <Video className="w-6 h-6 text-red-400" />;
    if (['mp3', 'wav', 'ogg'].includes(ext || '')) return <Music className="w-6 h-6 text-green-400" />;
    return <FileText className="w-6 h-6 text-slate-400" />;
  };

  return (
    <div className="h-full flex flex-col bg-slate-900 text-white font-mono">
      {/* Header */}
      <div className="flex items-center gap-2 p-3 bg-slate-950 border-b border-slate-800">
        <button 
          onClick={handleUpDir} 
          disabled={!currentPath}
          className="p-2 hover:bg-slate-800 rounded disabled:opacity-30 transition-colors"
        >
          <ChevronLeft className="w-5 h-5" />
        </button>
        <div className="flex-1 overflow-hidden">
          <div className="text-xs text-slate-400">Location</div>
          <div className="truncate font-medium flex items-center gap-1">
            <HardDrive className="w-3 h-3 text-slate-500" />
            /storage/{currentPath || 'root'}
          </div>
        </div>
        <button 
          onClick={() => loadFiles(currentPath)} 
          className="p-2 hover:bg-slate-800 rounded transition-colors"
        >
          <RefreshCw className={`w-5 h-5 ${loading ? 'animate-spin' : ''}`} />
        </button>
      </div>

      {/* Error State */}
      {error && (
        <div className="p-4 m-4 bg-red-500/10 border border-red-500/30 rounded flex items-center gap-3 text-red-400">
          <AlertTriangle className="w-6 h-6" />
          <div className="text-sm">{error}</div>
        </div>
      )}

      {/* File List */}
      <div className="flex-1 overflow-auto p-2">
        {files.length === 0 && !loading && !error && (
          <div className="text-center py-10 text-slate-500 text-sm">
            Folder is empty
          </div>
        )}
        
        <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-2">
          {files.map((file, idx) => (
            <button
              key={idx}
              onClick={() => handleFileClick(file)}
              className="flex items-center gap-3 p-3 rounded-lg hover:bg-slate-800 transition-colors text-left group"
            >
              <div className="w-10 h-10 rounded-lg bg-slate-950 flex items-center justify-center border border-slate-800 group-hover:border-slate-700">
                {getFileIcon(file)}
              </div>
              <div className="flex-1 min-w-0">
                <div className="truncate text-sm font-medium group-hover:text-blue-400 transition-colors">
                  {file.name}
                </div>
                <div className="text-xs text-slate-500 flex gap-2">
                  {file.size ? (file.size / 1024).toFixed(1) + ' KB' : ''} 
                </div>
              </div>
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}
