import React from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import Layout from './components/Layout';
import HomePage from './components/HomePage';
import TorrentPage from './components/TorrentPage';
import RecentPage from './components/RecentPage';
import SettingsPage from './components/SettingsPage';
import './App.css';

function App() {
  return (
    <Router>
      <Routes>
        <Route path="/" element={<Layout />}>
          <Route index element={<HomePage />} />
          <Route path="torrent/:torrentHash" element={<TorrentPage />} />
          <Route path="recent" element={<RecentPage />} />
          <Route path="settings" element={<SettingsPage />} />
        </Route>
      </Routes>
    </Router>
  );
}

export default App;

  // Build file tree from flat file list
  const buildFileTree = (files) => {
    const tree = {}
    files.forEach((file, index) => {
      const parts = file.name.split('/')
      let current = tree
      
      for (let i = 0; i < parts.length - 1; i++) {
        const folder = parts[i]
        if (!current[folder]) {
          current[folder] = { type: 'folder', children: {} }
        }
        current = current[folder].children
      }
      
      const fileName = parts[parts.length - 1]
      current[fileName] = { 
        type: 'file', 
        ...file, 
        originalIndex: index 
      }
    })
    return tree
  }

  // Save video progress to localStorage
  const saveVideoProgress = (torrentHash, fileName, progress, duration) => {
    const key = `progress_${torrentHash}_${fileName}`
    const data = {
      progress,
      duration,
      timestamp: Date.now(),
      percentage: (progress / duration) * 100
    }
    localStorage.setItem(key, JSON.stringify(data))
  }

  // Get saved video progress
  const getSavedProgress = (torrentHash, fileName) => {
    const key = `progress_${torrentHash}_${fileName}`
    const data = localStorage.getItem(key)
    return data ? JSON.parse(data) : null
  }

  const addTorrent = async () => {
    if (!torrentInput.trim()) return
    setLoading(true)
    setFileTree({}) // Clear previous files
    setFilesLoading(false)
    
    try {
      console.log('Adding torrent:', torrentInput)
      const response = await fetch('/api/torrents', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ torrentId: torrentInput })
      })
      
      const data = await response.json()
      console.log('Torrent add response:', data)
      if (data.infoHash) {
        setCurrentTorrent(data.infoHash)
        console.log('Current torrent set to:', data.infoHash)
        await loadFiles(data.infoHash)
        await loadTorrentStatus(data.infoHash)
        await loadActiveTorrents() // Refresh torrent list
        setTorrentInput('')
      }
    } catch (error) {
      console.error('Error adding torrent:', error)
    }
    
    setLoading(false)
  }

  const addTorrentFile = async (file) => {
    if (!file) return
    setLoading(true)
    setFileTree({}) // Clear previous files
    setFilesLoading(false)
    
    try {
      console.log('Adding torrent file:', file.name)
      const formData = new FormData()
      formData.append('torrentFile', file)
      
      const response = await fetch('/api/torrents/upload', {
        method: 'POST',
        body: formData
      })
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }
      
      const data = await response.json()
      console.log('Torrent file add response:', data)
      
      if (data.infoHash) {
        setCurrentTorrent(data.infoHash)
        console.log('Current torrent set to:', data.infoHash)
        await loadFiles(data.infoHash)
        await loadTorrentStatus(data.infoHash)
        await loadActiveTorrents() // Refresh torrent list
      }
    } catch (error) {
      console.error('Error adding torrent file:', error)
    }
    
    setLoading(false)
  }

  const handleFileSelect = (event) => {
    const file = event.target.files[0]
    if (file && file.name.endsWith('.torrent')) {
      addTorrentFile(file)
    } else {
      alert('Please select a valid .torrent file')
    }
    // Reset the input value so the same file can be selected again
    event.target.value = ''
  }

  const loadActiveTorrents = async () => {
    try {
      const response = await fetch('/api/torrents')
      const data = await response.json()
      setActiveTorrents(data.torrents || [])
    } catch (error) {
      console.error('Error loading active torrents:', error)
      setActiveTorrents([])
    }
  }

  const removeTorrent = async (infoHash) => {
    try {
      console.log('Removing torrent:', infoHash)
      const response = await fetch(`/api/torrents/${infoHash}`, {
        method: 'DELETE'
      })
      
      if (response.ok) {
        // If we're removing the current torrent, clear the UI
        if (currentTorrent === infoHash) {
          setCurrentTorrent(null)
          setFileTree({})
          setTorrentStatus(null)
          setVideoSrc(null)
          setCurrentFile(null)
        }
        
        // Reload the torrent list
        await loadActiveTorrents()
      }
    } catch (error) {
      console.error('Error removing torrent:', error)
    }
  }

  const clearAllTorrents = async () => {
    try {
      console.log('Clearing all torrents')
      const response = await fetch('/api/torrents', {
        method: 'DELETE'
      })
      
      if (response.ok) {
        // Clear all UI state
        setCurrentTorrent(null)
        setFileTree({})
        setTorrentStatus(null)
        setVideoSrc(null)
        setCurrentFile(null)
        setActiveTorrents([])
      }
    } catch (error) {
      console.error('Error clearing torrents:', error)
    }
  }

  const switchToTorrent = async (infoHash) => {
    console.log('Switching to torrent:', infoHash)
    setCurrentTorrent(infoHash)
    setVideoSrc(null)
    setCurrentFile(null)
    await loadFiles(infoHash)
    await loadTorrentStatus(infoHash)
    setShowTorrentList(false)
  }

  // Load active torrents when component mounts
  useEffect(() => {
    loadActiveTorrents()
    loadCacheStats()
  }, [])

  const loadCacheStats = async () => {
    try {
      const response = await fetch('/api/cache/stats')
      const data = await response.json()
      console.log('Cache stats loaded:', data) // Debug log
      setCacheStats(prev => ({
        ...prev,
        totalSize: data.totalSize,
        totalSizeFormatted: data.totalSizeFormatted,
        fileCount: data.fileCount,
        oldestFile: data.oldestFile,
        activeTorrents: data.activeTorrents,
        totalDownloaded: data.totalDownloaded,
        totalDownloadedFormatted: data.totalDownloadedFormatted
      }))
    } catch (error) {
      console.error('Error loading cache stats:', error)
    }
  }

  const clearCache = async () => {
    if (!confirm('Are you sure you want to clear all cache data? This will remove all active torrents and downloaded data.')) {
      return
    }
    
    try {
      const response = await fetch('/api/cache/clear', { method: 'POST' })
      const data = await response.json()
      
      if (response.ok) {
        const message = `Cache cleared successfully!\n\n` +
          `📁 Files deleted: ${data.deletedFiles}\n` +
          `💾 Disk space freed: ${data.deletedSizeFormatted}\n` +
          `🗑️ Torrents destroyed: ${data.destroyedTorrents}\n` +
          `🧠 Memory freed: ${data.freedFromTorrentsFormatted}\n` +
          `📊 Total freed: ${data.totalFreedFormatted}`
        
        alert(message)
        
        // Clear UI state since all torrents are destroyed
        setCurrentTorrent(null)
        setFileTree({})
        setTorrentStatus(null)
        setVideoSrc(null)
        setCurrentFile(null)
        setActiveTorrents([])
        
        await loadCacheStats()
      }
    } catch (error) {
      console.error('Error clearing cache:', error)
      alert('Failed to clear cache')
    }
  }

  const clearOldCache = useCallback(async (days = 7) => {
    try {
      const response = await fetch('/api/cache/clear-old', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ days })
      })
      const data = await response.json()
      
      if (response.ok) {
        console.log(`Auto-cleared old cache: ${data.deletedFiles} files, ${data.deletedSizeFormatted} freed`)
        await loadCacheStats()
      }
    } catch (error) {
      console.error('Error clearing old cache:', error)
    }
  }, [])

  const debugCache = async () => {
    try {
      const response = await fetch('/api/cache/debug')
      const data = await response.json()
      console.log('Cache debug info:', data)
      
      let message = "🔍 Cache Debug Information:\n\n"
      message += `📁 Existing cache directories (${data.existingDirs.length}):\n`
      
      data.existingDirs.forEach(dir => {
        const content = data.dirContents[dir]
        message += `  ${dir}\n`
        message += `    Files: ${content.fileCount}, Size: ${content.totalSizeFormatted}\n`
      })
      
      message += `\n🎬 Active torrents: ${data.clientInfo.activeTorrents}\n`
      data.clientInfo.torrents.forEach(t => {
        message += `  ${t.name}: ${formatBytes(t.downloaded)} (${(t.progress * 100).toFixed(1)}%)\n`
        message += `    Path: ${t.path}\n`
      })
      
      alert(message)
    } catch (error) {
      console.error('Error getting debug info:', error)
      alert('Failed to get debug info')
    }
  }

  // Auto-clear old cache on startup
  useEffect(() => {
    if (cacheStats.autoClearEnabled) {
      clearOldCache(cacheStats.autoClearDays)
    }
  }, [cacheStats.autoClearEnabled, cacheStats.autoClearDays, clearOldCache])

  // Refresh cache stats when torrents or torrent status changes
  useEffect(() => {
    if (showSettings) {
      loadCacheStats()
    }
  }, [showSettings, currentTorrent, torrentStatus])

  // Refresh cache stats periodically when settings are open
  useEffect(() => {
    if (showSettings) {
      const interval = setInterval(() => {
        loadCacheStats()
      }, 3000) // Refresh every 3 seconds
      
      return () => clearInterval(interval)
    }
  }, [showSettings])

  const loadFiles = async (infoHash) => {
    try {
      setFilesLoading(true)
      console.log('Loading files for torrent:', infoHash)
      const response = await fetch(`/api/torrents/${infoHash}/files`)
      const data = await response.json()
      console.log('Files response:', data)
      
      if (data.files) {
        // New backend format with ready status
        if (data.ready && data.files.length > 0) {
          const tree = buildFileTree(data.files)
          console.log('File tree built:', tree)
          setFileTree(tree)
          setFilesLoading(false)
        } else if (!data.ready) {
          console.log('Torrent not ready yet, retrying in 1 second...')
          // Retry after 1 second if torrent isn't ready
          setTimeout(() => loadFiles(infoHash), 1000)
        }
      } else {
        // Old backend format (fallback)
        if (data.length > 0) {
          const tree = buildFileTree(data)
          console.log('File tree built:', tree)
          setFileTree(tree)
          setFilesLoading(false)
        }
      }
    } catch (error) {
      console.error('Error loading files:', error)
      setFilesLoading(false)
    }
  }

  const loadTorrentStatus = async (infoHash) => {
    try {
      const response = await fetch(`/api/torrents/${infoHash}/status`)
      const status = await response.json()
      setTorrentStatus(status)
    } catch (error) {
      console.error('Error loading status:', error)
    }
  }

  // Poll for torrent status updates
  useEffect(() => {
    if (!currentTorrent) return
    
    const interval = setInterval(() => {
      loadTorrentStatus(currentTorrent)
    }, 2000)
    
    return () => clearInterval(interval)
  }, [currentTorrent])

  const streamFile = (file) => {
    const streamUrl = `/api/torrents/${currentTorrent}/files/${file.originalIndex}/stream`
    
    // Check for saved progress
    const saved = getSavedProgress(currentTorrent, file.name)
    if (saved && saved.percentage > 5 && saved.percentage < 95) {
      setSavedProgress(saved)
      setShowProgressPrompt(true)
    }
    
    setVideoSrc(streamUrl)
    setCurrentFile(file)
    setIsModalOpen(true)  // Open video in modal
  }

  const resumeFromSaved = () => {
    setVideoProgress(savedProgress.progress)
    setShowProgressPrompt(false)
    setSavedProgress(null)
    setIsModalOpen(true)  // Open modal after decision
  }

  const startFromBeginning = () => {
    setVideoProgress(0)
    setShowProgressPrompt(false)
    setSavedProgress(null)
    setIsModalOpen(true)  // Open modal after decision
  }

  const closeModal = () => {
    setIsModalOpen(false)
    setVideoSrc(null)
    setCurrentFile(null)
  }

  const downloadFile = (file) => {
    const downloadUrl = `/api/torrents/${currentTorrent}/files/${file.originalIndex}/download`
    const link = document.createElement('a')
    link.href = downloadUrl
    link.download = file.name
    link.click()
  }

  const toggleFolder = (path) => {
    const newExpanded = new Set(expandedFolders)
    if (newExpanded.has(path)) {
      newExpanded.delete(path)
    } else {
      newExpanded.add(path)
    }
    setExpandedFolders(newExpanded)
  }

  const renderFileTree = (tree, path = '') => {
    return Object.entries(tree).map(([name, item]) => {
      const currentPath = path ? `${path}/${name}` : name
      
      if (item.type === 'folder') {
        const isExpanded = expandedFolders.has(currentPath)
        return (
          <div key={currentPath} className="file-tree-item">
            <div 
              className="folder-item"
              onClick={() => toggleFolder(currentPath)}
            >
              {isExpanded ? <ChevronDown size={16} /> : <ChevronRight size={16} />}
              <Folder size={16} />
              <span>{name}</span>
            </div>
            {isExpanded && (
              <div className="folder-contents">
                {renderFileTree(item.children, currentPath)}
              </div>
            )}
          </div>
        )
      } else {
        return (
          <div key={currentPath} className="file-tree-item">
            <div className="file-item">
              <div className="file-info">
                <File size={16} />
                <span className="file-name">{name}</span>
                <span className="file-size">
                  {(item.length / 1024 / 1024).toFixed(1)} MB
                </span>
              </div>
              <div className="file-actions">
                {item.isVideo && (
                  <button 
                    onClick={() => streamFile(item)}
                    className="stream-button"
                  >
                    <Play size={14} /> Stream
                  </button>
                )}
                <button 
                  onClick={() => downloadFile(item)}
                  className="download-button"
                >
                  <Download size={14} /> Download
                </button>
              </div>
            </div>
          </div>
        )
      }
    })
  }

  const formatBytes = (bytes) => {
    if (bytes === 0) return '0 B'
    const k = 1024
    const sizes = ['B', 'KB', 'MB', 'GB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))
    return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i]
  }

  const formatSpeed = (bytesPerSecond) => {
    return formatBytes(bytesPerSecond) + '/s'
  }

  return (
    <div className="app">
      <header className="app-header">
        <div className="header-content">
          <div className="header-title">
            <h1>🌱 Seedbox Lite</h1>
            <p>Modern torrent client for streaming and downloading</p>
          </div>
          
          <button 
            onClick={() => setShowSettings(!showSettings)}
            className="settings-button"
          >
            <Settings size={20} />
            Settings
          </button>
        </div>
      </header>

      {/* Settings Panel */}
      {showSettings && (
        <div className="settings-panel">
          <div className="settings-header">
            <h3><Database size={20} /> Cache & Storage Management</h3>
          </div>
          
          <div className="settings-content">
            {/* Cache Statistics */}
            <div className="settings-section">
              <div className="section-header">
                <h4>📊 Current Cache Usage</h4>
                <button 
                  onClick={loadCacheStats}
                  className="refresh-button"
                >
                  🔄 Refresh
                </button>
              </div>
              <div className="stats-grid">
                <div className="stat-item">
                  <HardDrive size={16} />
                  <span>Cache Size: {cacheStats.totalSizeFormatted || '0 MB'}</span>
                </div>
                <div className="stat-item">
                  <Download size={16} />
                  <span>Downloaded: {cacheStats.totalDownloadedFormatted || '0 MB'}</span>
                </div>
                <div className="stat-item">
                  <File size={16} />
                  <span>Cache Files: {cacheStats.fileCount || 0}</span>
                </div>
                <div className="stat-item">
                  <Activity size={16} />
                  <span>Active Torrents: {cacheStats.activeTorrents || 0}</span>
                </div>
                {cacheStats.oldestFile && (
                  <div className="stat-item">
                    <Calendar size={16} />
                    <span>Oldest File: {cacheStats.oldestFile.age} days ago</span>
                  </div>
                )}
              </div>
            </div>

            {/* Cache Actions */}
            <div className="settings-section">
              <h4>🧹 Cache Management</h4>
              <div className="cache-actions">
                <button 
                  onClick={() => clearOldCache(7)}
                  className="action-button clear-old"
                >
                  <Calendar size={16} />
                  Clear Files Older Than 7 Days
                </button>
                
                <button 
                  onClick={clearCache}
                  className="action-button clear-all"
                >
                  <Trash2 size={16} />
                  Clear All Cache Data
                </button>
                
                <button 
                  onClick={debugCache}
                  className="action-button debug"
                >
                  🔍 Debug Cache Locations
                </button>
              </div>
            </div>

            {/* Auto-Clear Settings */}
            <div className="settings-section">
              <h4>⚡ Auto-Cleanup Settings</h4>
              <div className="auto-clear-settings">
                <label className="setting-item">
                  <input 
                    type="checkbox" 
                    checked={cacheStats.autoClearEnabled}
                    onChange={(e) => setCacheStats(prev => ({
                      ...prev, 
                      autoClearEnabled: e.target.checked
                    }))}
                  />
                  <span>Auto-clear old files on startup</span>
                </label>
                
                <label className="setting-item">
                  <span>Clear files older than:</span>
                  <select 
                    value={cacheStats.autoClearDays}
                    onChange={(e) => setCacheStats(prev => ({
                      ...prev, 
                      autoClearDays: parseInt(e.target.value)
                    }))}
                  >
                    <option value={1}>1 day</option>
                    <option value={3}>3 days</option>
                    <option value={7}>7 days</option>
                    <option value={14}>14 days</option>
                    <option value={30}>30 days</option>
                  </select>
                </label>
              </div>
            </div>

            {/* Info Section */}
            <div className="settings-section">
              <h4>ℹ️ About Cache Data</h4>
              <div className="info-text">
                <p><strong>What is cached:</strong> Torrent pieces downloaded for streaming are temporarily stored to enable seeking and buffering.</p>
                <p><strong>Where it's stored:</strong> <code>~/.webtorrent/</code> directory on your system.</p>
                <p><strong>Why it exists:</strong> Enables smooth video playback, seeking, and resuming streams without re-downloading.</p>
                <p><strong>Safe to clear:</strong> Yes! Cache will be rebuilt as needed for streaming.</p>
              </div>
            </div>
          </div>
        </div>
      )}

      <main className="main-content">
        <div className="torrent-input-section">
          <div className="input-group">
            <input
              type="text"
              value={torrentInput}
              onChange={(e) => setTorrentInput(e.target.value)}
              placeholder="Enter magnet link or torrent URL"
              className="torrent-input"
              onKeyPress={(e) => e.key === 'Enter' && addTorrent()}
            />
            <button 
              onClick={addTorrent} 
              disabled={loading}
              className="add-button"
            >
              {loading ? '⏳' : '➕'} Add Torrent
            </button>
          </div>
          
          <div className="file-upload-section">
            <input
              type="file"
              accept=".torrent"
              onChange={handleFileSelect}
              style={{ display: 'none' }}
              id="torrent-file-input"
            />
            <label 
              htmlFor="torrent-file-input" 
              className="upload-button"
              style={{ 
                cursor: loading ? 'not-allowed' : 'pointer',
                opacity: loading ? 0.6 : 1
              }}
            >
              <Upload size={16} />
              Upload .torrent file
            </label>
          </div>
        </div>

        {/* Torrent Management Section */}
        {activeTorrents.length > 0 && (
          <div className="torrent-management-section">
            <div className="section-header">
              <button 
                onClick={() => setShowTorrentList(!showTorrentList)}
                className="toggle-button"
              >
                <List size={16} />
                {showTorrentList ? 'Hide' : 'Show'} Active Torrents ({activeTorrents.length})
              </button>
              
              {activeTorrents.length > 1 && (
                <button 
                  onClick={clearAllTorrents}
                  className="clear-button"
                >
                  <Trash2 size={16} />
                  Clear All
                </button>
              )}
            </div>

            {showTorrentList && (
              <div className="torrent-list">
                {activeTorrents.map((torrent) => (
                  <div 
                    key={torrent.infoHash} 
                    className={`torrent-item ${currentTorrent === torrent.infoHash ? 'active' : ''}`}
                  >
                    <div className="torrent-info">
                      <h4>{torrent.name}</h4>
                      <div className="torrent-stats">
                        <span>{torrent.fileCount} files</span>
                        <span>{(torrent.size / 1024 / 1024 / 1024).toFixed(1)} GB</span>
                        <span>{(torrent.progress * 100).toFixed(1)}% ready</span>
                        <span>{torrent.peers} peers</span>
                      </div>
                    </div>
                    
                    <div className="torrent-actions">
                      {currentTorrent !== torrent.infoHash && (
                        <button 
                          onClick={() => switchToTorrent(torrent.infoHash)}
                          className="switch-button"
                        >
                          Switch
                        </button>
                      )}
                      
                      <button 
                        onClick={() => removeTorrent(torrent.infoHash)}
                        className="remove-button"
                      >
                        <Trash2 size={14} />
                      </button>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        )}

        {torrentStatus && (
          <div className="status-section">
            <div className="status-card">
              <h3>{torrentStatus.name}</h3>
              <div className="status-grid">
                <div className="status-item">
                  <Activity size={16} />
                  <span>Progress: {(torrentStatus.progress * 100).toFixed(1)}%</span>
                </div>
                <div className="status-item">
                  <Users size={16} />
                  <span>Peers: {torrentStatus.peers}</span>
                </div>
                <div className="status-item">
                  <Download size={16} />
                  <span>↓ {formatSpeed(torrentStatus.downloadSpeed)}</span>
                </div>
                <div className="status-item">
                  <span>Downloaded: {formatBytes(torrentStatus.downloaded)}</span>
                </div>
              </div>
              <div className="progress-bar">
                <div 
                  className="progress-fill" 
                  style={{ width: `${torrentStatus.progress * 100}%` }}
                ></div>
              </div>
            </div>
          </div>
        )}

        {Object.keys(fileTree).length > 0 && (
          <div className="files-section">
            <h2>📁 Files & Folders</h2>
            <div className="file-tree">
              {renderFileTree(fileTree)}
            </div>
          </div>
        )}

        {currentTorrent && Object.keys(fileTree).length === 0 && filesLoading && (
          <div className="files-section">
            <h2>⏳ Loading Files...</h2>
            <p>Please wait while we load the torrent files...</p>
            <div className="progress-bar">
              <div className="progress-fill" style={{ width: '50%', animation: 'pulse 2s infinite' }}></div>
            </div>
          </div>
        )}

        {currentTorrent && Object.keys(fileTree).length === 0 && !filesLoading && (
          <div className="files-section">
            <h2>❌ No Files Found</h2>
            <p>Unable to load files from this torrent. Please try another torrent.</p>
          </div>
        )}

        {/* Video Modal */}
        <VideoModal 
          isOpen={isModalOpen} 
          onClose={closeModal}
          title={currentFile?.name || 'Video Player'}
        >
          {videoSrc && (
            <VideoPlayer
              src={videoSrc}
              title={currentFile?.name || 'Video'}
              initialTime={videoProgress}
              torrentHash={currentTorrent}
              fileIndex={currentFile?.index}
              onTimeUpdate={(time) => {
                if (currentFile && currentTorrent) {
                  const duration = document.querySelector('video')?.duration || 0;
                  const percentage = duration > 0 ? (time / duration) * 100 : 0;
                  saveVideoProgress(currentTorrent, currentFile.name, time, percentage);
                }
              }}
              onProgress={(bufferedPercent) => {
                // Optional: handle buffer progress
                console.log(`Buffered: ${bufferedPercent}%`);
              }}
            />
          )}
        </VideoModal>

        {showProgressPrompt && savedProgress && (
          <div className="progress-prompt-overlay">
            <div className="progress-prompt">
              <Clock size={24} />
              <h3>Resume Playback?</h3>
              <p>You were watching this video at {savedProgress.percentage.toFixed(1)}% ({Math.floor(savedProgress.progress / 60)}:{Math.floor(savedProgress.progress % 60).toString().padStart(2, '0')})</p>
              <div className="prompt-buttons">
                <button onClick={resumeFromSaved} className="resume-button">
                  Resume
                </button>
                <button onClick={startFromBeginning} className="restart-button">
                  Start Over
                </button>
              </div>
            </div>
          </div>
        )}
      </main>
    </div>
  )
}

export default App
