/**
 * Duplicate file management component for SOUND UI
 */

class DuplicateManager {
  constructor() {
    this.duplicateGroups = [];
    this.currentGroup = 0;
    this.selectedForDeletion = new Set();
  }

  /**
   * Initialize the duplicate manager
   */
  async initialize() {
    console.log("Initializing duplicate manager...");

    // Show loading state
    if (window.loadingManager) {
      window.loadingManager.showLoader("duplicates", "Scanning for duplicates...");
    }

    try {
      await this.loadDuplicates();
      this.renderUI();

      // Hide loading state
      if (window.loadingManager) {
        window.loadingManager.hideLoader("duplicates");
      }
    } catch (error) {
      console.error("Failed to initialize duplicate manager:", error);
      if (window.loadingManager) {
        window.loadingManager.hideLoader("duplicates");
      }
    }
  }

  /**
   * Load duplicates from the server
   */
  async loadDuplicates() {
    try {
      const response = await fetch("/api/duplicates");
      const data = await response.json();

      this.duplicateGroups = data.duplicates || [];
      console.log(`Found ${this.duplicateGroups.length} duplicate groups`);
    } catch (error) {
      console.error("Failed to load duplicates:", error);
      this.duplicateGroups = [];
    }
  }

  /**
   * Render the duplicate manager UI
   */
  renderUI() {
    const container = document.getElementById("duplicate-manager");
    if (!container) return;

    if (this.duplicateGroups.length === 0) {
      container.innerHTML = `
        <div class="empty-state">
          <i class="fas fa-check-circle"></i>
          <h3>No Duplicates Found</h3>
          <p>Your music library doesn't contain any duplicate tracks.</p>
          <button class="btn btn-primary" onclick="duplicateManager.scanForDuplicates()">
            <i class="fas fa-sync"></i> Rescan Library
          </button>
        </div>
      `;
      return;
    }

    const stats = this.calculateStats();
    const currentGroup = this.duplicateGroups[this.currentGroup];

    container.innerHTML = `
      <div class="duplicate-header">
        <h2>Duplicate File Manager</h2>
        <div class="duplicate-stats">
          <div class="stat">
            <span class="stat-label">Duplicate Groups:</span>
            <span class="stat-value">${this.duplicateGroups.length}</span>
          </div>
          <div class="stat">
            <span class="stat-label">Total Duplicates:</span>
            <span class="stat-value">${stats.totalDuplicates}</span>
          </div>
          <div class="stat">
            <span class="stat-label">Wasted Space:</span>
            <span class="stat-value">${this.formatFileSize(stats.wastedSpace)}</span>
          </div>
        </div>
      </div>

      <div class="duplicate-navigation">
        <button class="btn btn-secondary" 
          onclick="duplicateManager.previousGroup()" 
          ${this.currentGroup === 0 ? "disabled" : ""}>
          <i class="fas fa-chevron-left"></i> Previous
        </button>
        <span class="group-indicator">
          Group ${this.currentGroup + 1} of ${this.duplicateGroups.length}
        </span>
        <button class="btn btn-secondary" 
          onclick="duplicateManager.nextGroup()"
          ${this.currentGroup === this.duplicateGroups.length - 1 ? "disabled" : ""}>
          Next <i class="fas fa-chevron-right"></i>
        </button>
      </div>

      <div class="duplicate-group">
        <div class="group-header">
          <h3>Duplicate Tracks</h3>
          <div class="auto-select-buttons">
            <button class="btn btn-sm" onclick="duplicateManager.autoSelectLowestQuality()">
              <i class="fas fa-filter"></i> Select Lower Quality
            </button>
            <button class="btn btn-sm" onclick="duplicateManager.autoSelectSmallest()">
              <i class="fas fa-compress"></i> Select Smallest
            </button>
            <button class="btn btn-sm" onclick="duplicateManager.clearSelection()">
              <i class="fas fa-times"></i> Clear Selection
            </button>
          </div>
        </div>
        
        <div class="track-list">
          ${currentGroup.tracks.map((track, index) => this.renderTrack(track, index)).join("")}
        </div>
      </div>

      <div class="duplicate-actions">
        <div class="selected-info">
          <span>${this.selectedForDeletion.size} tracks selected for deletion</span>
          ${
            this.selectedForDeletion.size > 0
              ? `
            <span class="space-saved">
              (${this.formatFileSize(this.calculateSelectedSize())} will be freed)
            </span>
          `
              : ""
          }
        </div>
        <div class="action-buttons">
          <button class="btn btn-danger" 
            onclick="duplicateManager.deleteSelected()"
            ${this.selectedForDeletion.size === 0 ? "disabled" : ""}>
            <i class="fas fa-trash"></i> Delete Selected
          </button>
          <button class="btn btn-secondary" onclick="duplicateManager.skipGroup()">
            <i class="fas fa-forward"></i> Skip Group
          </button>
        </div>
      </div>
    `;
  }

  /**
   * Render a single track
   */
  renderTrack(track, index) {
    const isSelected = this.selectedForDeletion.has(track.path);
    const isBest = index === 0; // First track is highest quality

    return `
      <div class="duplicate-track ${isSelected ? "selected" : ""} ${isBest ? "best-quality" : ""}">
        <div class="track-checkbox">
          <input type="checkbox" 
            id="track-${index}" 
            ${isSelected ? "checked" : ""}
            ${isBest ? "disabled" : ""}
            onchange="duplicateManager.toggleTrackSelection('${track.path}')">
        </div>
        <div class="track-info">
          <div class="track-path">${this.getFilename(track.path)}</div>
          <div class="track-details">
            <span class="quality-score">
              <i class="fas fa-star"></i> Quality: ${track.quality}/100
              ${isBest ? '<span class="best-badge">BEST</span>' : ""}
            </span>
            <span class="file-size">
              <i class="fas fa-file"></i> ${this.formatFileSize(track.size)}
            </span>
            <span class="modified-date">
              <i class="fas fa-calendar"></i> ${this.formatDate(track.modified)}
            </span>
          </div>
          <div class="full-path">${track.path}</div>
        </div>
        <div class="track-actions">
          <button class="btn btn-sm" onclick="duplicateManager.playTrack('${track.path}')" title="Preview">
            <i class="fas fa-play"></i>
          </button>
          <button class="btn btn-sm" onclick="duplicateManager.showInFinder('${track.path}')" title="Show in Finder">
            <i class="fas fa-folder-open"></i>
          </button>
        </div>
      </div>
    `;
  }

  /**
   * Toggle track selection
   */
  toggleTrackSelection(path) {
    if (this.selectedForDeletion.has(path)) {
      this.selectedForDeletion.delete(path);
    } else {
      this.selectedForDeletion.add(path);
    }
    this.renderUI();
  }

  /**
   * Auto-select tracks with lowest quality
   */
  autoSelectLowestQuality() {
    const currentGroup = this.duplicateGroups[this.currentGroup];
    this.selectedForDeletion.clear();

    // Select all but the first (highest quality) track
    for (let i = 1; i < currentGroup.tracks.length; i++) {
      this.selectedForDeletion.add(currentGroup.tracks[i].path);
    }

    this.renderUI();
  }

  /**
   * Auto-select smallest files
   */
  autoSelectSmallest() {
    const currentGroup = this.duplicateGroups[this.currentGroup];
    this.selectedForDeletion.clear();

    // Find the largest file
    let largestIndex = 0;
    let largestSize = currentGroup.tracks[0].size;

    for (let i = 1; i < currentGroup.tracks.length; i++) {
      if (currentGroup.tracks[i].size > largestSize) {
        largestSize = currentGroup.tracks[i].size;
        largestIndex = i;
      }
    }

    // Select all but the largest file
    for (let i = 0; i < currentGroup.tracks.length; i++) {
      if (i !== largestIndex) {
        this.selectedForDeletion.add(currentGroup.tracks[i].path);
      }
    }

    this.renderUI();
  }

  /**
   * Clear selection
   */
  clearSelection() {
    this.selectedForDeletion.clear();
    this.renderUI();
  }

  /**
   * Navigate to previous group
   */
  previousGroup() {
    if (this.currentGroup > 0) {
      this.currentGroup--;
      this.selectedForDeletion.clear();
      this.renderUI();
    }
  }

  /**
   * Navigate to next group
   */
  nextGroup() {
    if (this.currentGroup < this.duplicateGroups.length - 1) {
      this.currentGroup++;
      this.selectedForDeletion.clear();
      this.renderUI();
    }
  }

  /**
   * Skip current group
   */
  skipGroup() {
    if (this.currentGroup < this.duplicateGroups.length - 1) {
      this.nextGroup();
    } else {
      // All groups processed
      this.showCompletionMessage();
    }
  }

  /**
   * Delete selected tracks
   */
  async deleteSelected() {
    const paths = Array.from(this.selectedForDeletion);
    if (paths.length === 0) return;

    const confirmed = confirm(
      `Are you sure you want to delete ${paths.length} duplicate track(s)?\n\nThis action cannot be undone.`,
    );
    if (!confirmed) return;

    // Show progress
    if (window.loadingManager) {
      window.loadingManager.showProgress("delete", 0, `Deleting ${paths.length} tracks...`);
    }

    try {
      const response = await fetch("/api/duplicates/delete", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ paths }),
      });

      if (!response.ok) {
        throw new Error("Failed to delete tracks");
      }

      const result = await response.json();

      // Remove deleted tracks from current group
      const currentGroup = this.duplicateGroups[this.currentGroup];
      currentGroup.tracks = currentGroup.tracks.filter(
        (track) => !this.selectedForDeletion.has(track.path),
      );

      // Clear selection
      this.selectedForDeletion.clear();

      // If only one track left, remove the group
      if (currentGroup.tracks.length <= 1) {
        this.duplicateGroups.splice(this.currentGroup, 1);
        if (this.currentGroup >= this.duplicateGroups.length && this.currentGroup > 0) {
          this.currentGroup--;
        }
      }

      // Hide progress
      if (window.loadingManager) {
        window.loadingManager.hideProgress("delete");
      }

      // Show success message
      this.showStatus(`Successfully deleted ${result.deleted} track(s)`, "success");

      // Re-render or show completion if no more duplicates
      if (this.duplicateGroups.length === 0) {
        this.renderUI();
      } else {
        this.renderUI();
      }
    } catch (error) {
      console.error("Failed to delete tracks:", error);
      if (window.loadingManager) {
        window.loadingManager.hideProgress("delete");
      }
      this.showStatus("Failed to delete tracks", "error");
    }
  }

  /**
   * Play a track preview
   */
  async playTrack(path) {
    try {
      await window.electronAPI.playAudio(path);
    } catch (error) {
      console.error("Failed to play track:", error);
    }
  }

  /**
   * Show track in file manager
   */
  async showInFinder(path) {
    try {
      await window.electronAPI.showInFinder(path);
    } catch (error) {
      console.error("Failed to show in finder:", error);
    }
  }

  /**
   * Scan for duplicates
   */
  async scanForDuplicates() {
    if (window.loadingManager) {
      window.loadingManager.showProgress("scan", 0, "Generating fingerprints...");
    }

    try {
      const response = await fetch("/api/duplicates/scan", {
        method: "POST",
      });

      if (!response.ok) {
        throw new Error("Failed to scan for duplicates");
      }

      // Set up SSE for progress updates
      const eventSource = new EventSource("/api/duplicates/scan/progress");

      eventSource.addEventListener("progress", (event) => {
        const data = JSON.parse(event.data);
        if (window.loadingManager) {
          const percent = Math.round((data.current / data.total) * 100);
          window.loadingManager.showProgress(
            "scan",
            percent,
            `Processing ${data.current} of ${data.total} tracks...`,
          );
        }
      });

      eventSource.addEventListener("complete", async (event) => {
        eventSource.close();
        if (window.loadingManager) {
          window.loadingManager.hideProgress("scan");
        }

        // Reload duplicates
        await this.loadDuplicates();
        this.renderUI();
      });

      eventSource.addEventListener("error", (event) => {
        eventSource.close();
        if (window.loadingManager) {
          window.loadingManager.hideProgress("scan");
        }
        this.showStatus("Scan failed", "error");
      });
    } catch (error) {
      console.error("Failed to scan for duplicates:", error);
      if (window.loadingManager) {
        window.loadingManager.hideProgress("scan");
      }
      this.showStatus("Failed to scan for duplicates", "error");
    }
  }

  /**
   * Show completion message
   */
  showCompletionMessage() {
    const container = document.getElementById("duplicate-manager");
    container.innerHTML = `
      <div class="completion-message">
        <i class="fas fa-check-circle"></i>
        <h3>All Duplicates Processed!</h3>
        <p>You've reviewed all duplicate groups in your library.</p>
        <button class="btn btn-primary" onclick="duplicateManager.initialize()">
          <i class="fas fa-redo"></i> Check Again
        </button>
      </div>
    `;
  }

  /**
   * Calculate statistics
   */
  calculateStats() {
    let totalDuplicates = 0;
    let wastedSpace = 0;

    for (const group of this.duplicateGroups) {
      if (group.tracks.length > 1) {
        totalDuplicates += group.tracks.length - 1;
        // Calculate wasted space (all but the best quality track)
        for (let i = 1; i < group.tracks.length; i++) {
          wastedSpace += group.tracks[i].size;
        }
      }
    }

    return { totalDuplicates, wastedSpace };
  }

  /**
   * Calculate size of selected tracks
   */
  calculateSelectedSize() {
    const currentGroup = this.duplicateGroups[this.currentGroup];
    let totalSize = 0;

    for (const track of currentGroup.tracks) {
      if (this.selectedForDeletion.has(track.path)) {
        totalSize += track.size;
      }
    }

    return totalSize;
  }

  /**
   * Format file size
   */
  formatFileSize(bytes) {
    if (bytes === 0) return "0 Bytes";
    const k = 1024;
    const sizes = ["Bytes", "KB", "MB", "GB", "TB"];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
  }

  /**
   * Format date
   */
  formatDate(timestamp) {
    return new Date(timestamp).toLocaleDateString();
  }

  /**
   * Get filename from path
   */
  getFilename(filepath) {
    return filepath.split(/[\\/]/).pop();
  }

  /**
   * Show status message
   */
  showStatus(message, type = "info") {
    const statusEl = document.getElementById("status-message");
    if (!statusEl) return;

    statusEl.textContent = message;
    statusEl.className = `alert alert-${type}`;
    statusEl.style.display = "flex";

    if (type !== "error") {
      setTimeout(() => {
        statusEl.style.display = "none";
      }, 5000);
    }
  }
}

// Create global instance
const duplicateManager = new DuplicateManager();

// Add required CSS
function injectDuplicateStyles() {
  if (document.getElementById("duplicate-styles")) return;

  const style = document.createElement("style");
  style.id = "duplicate-styles";
  style.textContent = `
    /* Duplicate Manager Styles */
    .duplicate-header {
      margin-bottom: 20px;
    }

    .duplicate-stats {
      display: flex;
      gap: 30px;
      margin-top: 10px;
    }

    .stat {
      display: flex;
      align-items: center;
      gap: 10px;
    }

    .stat-label {
      color: #666;
      font-size: 14px;
    }

    .stat-value {
      font-size: 20px;
      font-weight: bold;
      color: #3b82f6;
    }

    .duplicate-navigation {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 20px;
      margin-bottom: 20px;
      padding: 15px;
      background: #1a1a1a;
      border-radius: 8px;
    }

    .group-indicator {
      font-size: 16px;
      color: #e5e5e5;
    }

    .duplicate-group {
      background: #1a1a1a;
      border-radius: 8px;
      padding: 20px;
      margin-bottom: 20px;
    }

    .group-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;
    }

    .auto-select-buttons {
      display: flex;
      gap: 10px;
    }

    .track-list {
      display: flex;
      flex-direction: column;
      gap: 10px;
    }

    .duplicate-track {
      display: flex;
      align-items: center;
      gap: 15px;
      padding: 15px;
      background: #262626;
      border-radius: 6px;
      border: 2px solid transparent;
      transition: all 0.2s;
    }

    .duplicate-track:hover {
      background: #2a2a2a;
    }

    .duplicate-track.selected {
      border-color: #dc3545;
      background: rgba(220, 53, 69, 0.1);
    }

    .duplicate-track.best-quality {
      border-color: #28a745;
    }

    .track-checkbox {
      flex-shrink: 0;
    }

    .track-info {
      flex-grow: 1;
    }

    .track-path {
      font-weight: 500;
      margin-bottom: 5px;
    }

    .track-details {
      display: flex;
      gap: 20px;
      font-size: 13px;
      color: #999;
      margin-bottom: 5px;
    }

    .quality-score {
      display: flex;
      align-items: center;
      gap: 5px;
    }

    .best-badge {
      background: #28a745;
      color: white;
      padding: 2px 6px;
      border-radius: 3px;
      font-size: 11px;
      margin-left: 5px;
    }

    .full-path {
      font-size: 12px;
      color: #666;
      margin-top: 5px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .track-actions {
      display: flex;
      gap: 5px;
      flex-shrink: 0;
    }

    .duplicate-actions {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20px;
      background: #1a1a1a;
      border-radius: 8px;
    }

    .selected-info {
      display: flex;
      flex-direction: column;
      gap: 5px;
    }

    .space-saved {
      font-size: 13px;
      color: #28a745;
    }

    .action-buttons {
      display: flex;
      gap: 10px;
    }

    .empty-state,
    .completion-message {
      text-align: center;
      padding: 60px 20px;
    }

    .empty-state i,
    .completion-message i {
      font-size: 64px;
      color: #28a745;
      margin-bottom: 20px;
    }

    .empty-state h3,
    .completion-message h3 {
      font-size: 24px;
      margin-bottom: 10px;
    }

    .empty-state p,
    .completion-message p {
      color: #999;
      margin-bottom: 20px;
    }
  `;

  document.head.appendChild(style);
}

// Auto-inject styles
injectDuplicateStyles();

// Export for use
window.duplicateManager = duplicateManager;
