import SwiftUI
import Combine

enum GenerationState {
    case idle
    case generating
    case completed
    case error
}

struct GeneratedSong {
    let id = UUID()
    let title: String
    let artist: String
    let duration: TimeInterval
    let isGenerating: Bool
    let createdAt = Date()
    
    init(title: String, artist: String = "AI Generated", duration: TimeInterval = 120.0, isGenerating: Bool = true) {
        self.title = title
        self.artist = artist
        self.duration = duration
        self.isGenerating = isGenerating
    }
}

class SongGenerationManager: ObservableObject {
    static let shared = SongGenerationManager()
    
    @Published var generationState: GenerationState = .idle
    @Published var currentGeneratedSongs: [GeneratedSong] = []
    @Published var showToast: Bool = false
    @Published var showWorkspace: Bool = false
    @Published var showCreateSheet: Bool = false
    @Published var currentSongDescription: String = ""
    @Published var currentCreationMode: String = ""
    @Published var currentSongInfo: [String: Any] = [:]
    @Published var isEditingMode: Bool = false
    
    private init() {}
    
    // Start song generation process
    func startGeneration(with songInfo: [String: Any]) {
        print("🎵 Starting song generation with info: \(songInfo)")
        
        // Store song creation details
        self.currentSongInfo = songInfo
        self.currentCreationMode = songInfo["mode"] as? String ?? "simple"
        
        // Extract song description based on mode
        if let mode = songInfo["mode"] as? String, mode == "simple" {
            self.currentSongDescription = songInfo["songDescription"] as? String ?? ""
        } else {
            // For custom mode, combine style and lyrics descriptions
            let styleDescription = songInfo["styleDescription"] as? String ?? ""
            let lyricsDescription = songInfo["lyricsDescription"] as? String ?? ""
            if !styleDescription.isEmpty {
                self.currentSongDescription = styleDescription
            } else if !lyricsDescription.isEmpty {
                self.currentSongDescription = lyricsDescription
            } else {
                self.currentSongDescription = "Custom Song"
            }
        }
        
        // Create a generating song based on the song info
        let songTitle: String
        if let mode = songInfo["mode"] as? String, mode == "simple" {
            songTitle = "Untitled Song"
        } else {
            songTitle = "Custom Song"
        }
        
        let generatingSong = GeneratedSong(title: songTitle, isGenerating: true)
        
        DispatchQueue.main.async {
            self.generationState = .generating
            self.currentGeneratedSongs = [generatingSong]
            self.showToast = true
            
            // Simulate generation completing after 3 seconds
            DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {
                self.completeGeneration()
            }
        }
    }
    
    // Complete the generation process
    private func completeGeneration() {
        print("✅ Song generation completed")
        
        // Convert generating song to completed
        let completedSongs = currentGeneratedSongs.map { song in
            GeneratedSong(title: song.title, artist: song.artist, duration: song.duration, isGenerating: false)
        }
        
        DispatchQueue.main.async {
            self.generationState = .completed
            self.currentGeneratedSongs = completedSongs
        }
    }
    
    // Open workspace with current generation state
    func openWorkspace() {
        print("📱 Opening workspace with generation state: \(generationState)")
        DispatchQueue.main.async {
            self.showWorkspace = true
        }
    }
    
    // Close workspace
    func closeWorkspace() {
        DispatchQueue.main.async {
            self.showWorkspace = false
        }
    }
    
    // Hide toast
    func hideToast() {
        DispatchQueue.main.async {
            self.showToast = false
        }
    }
    
    // Start editing mode - opens create sheet with existing song details
    func startEditingMode() {
        print("📝 Starting edit mode with current song description: \(currentSongDescription)")
        DispatchQueue.main.async {
            self.isEditingMode = true
            self.showWorkspace = false
            self.showCreateSheet = true
        }
    }
    
    // Exit editing mode
    func exitEditingMode() {
        DispatchQueue.main.async {
            self.isEditingMode = false
            self.showCreateSheet = false
        }
    }
    
    // Reset generation state
    func reset() {
        DispatchQueue.main.async {
            self.generationState = .idle
            self.currentGeneratedSongs = []
            self.showToast = false
            self.showWorkspace = false
            self.showCreateSheet = false
            self.currentSongDescription = ""
            self.currentCreationMode = ""
            self.currentSongInfo = [:]
            self.isEditingMode = false
        }
    }
}