//
//  ContentView.swift
//  vibes
//
//  Created by Yamill Vallecillo on 6/30/25.
//

import SwiftUI

enum MainDestination {
    case create
    case lyricsEditor(lyrics: LyricsStructure, songTitle: String)
    case library
    case workspaces
    case workspace(workspaceTitle: String?, workspaceImageId: String?, chatSongs: [Song])
    case workspaceChat(workspaceTitle: String?, workspaceImageId: String?, chatSongs: [Song])
    case createView
}

extension MainDestination: Hashable {
    func hash(into hasher: inout Hasher) {
        switch self {
        case .create:
            hasher.combine(0)
        case .lyricsEditor(let lyrics, let songTitle):
            hasher.combine(1)
            hasher.combine(lyrics)
            hasher.combine(songTitle)
        case .library:
            hasher.combine(2)
        case .workspaces:
            hasher.combine(3)
        case .workspace(let workspaceTitle, let workspaceImageId, let chatSongs):
            hasher.combine(4)
            hasher.combine(workspaceTitle)
            hasher.combine(workspaceImageId)
            hasher.combine(chatSongs)
        case .workspaceChat(let workspaceTitle, let workspaceImageId, let chatSongs):
            hasher.combine(5)
            hasher.combine(workspaceTitle)
            hasher.combine(workspaceImageId)
            hasher.combine(chatSongs)
        case .createView:
            hasher.combine(6)
        }
    }
}

extension MainDestination: Equatable {
    static func == (lhs: MainDestination, rhs: MainDestination) -> Bool {
        switch (lhs, rhs) {
        case (.create, .create), (.library, .library), (.workspaces, .workspaces), (.createView, .createView):
            return true
        case (.lyricsEditor(let lLyrics, let lTitle), .lyricsEditor(let rLyrics, let rTitle)):
            return lLyrics == rLyrics && lTitle == rTitle
        case (.workspace(let lTitle, let lImageId, let lSongs), .workspace(let rTitle, let rImageId, let rSongs)):
            return lTitle == rTitle && lImageId == rImageId && lSongs == rSongs
        case (.workspaceChat(let lTitle, let lImageId, let lSongs), .workspaceChat(let rTitle, let rImageId, let rSongs)):
            return lTitle == rTitle && lImageId == rImageId && lSongs == rSongs
        default:
            return false
        }
    }
}

struct ContentView: View {
    @State private var selectedTab: NavTab = .hooks
    @State private var showCreateSheet = false
    @State private var toastVisible = false
    @State private var navigationPath = NavigationPath()
    @State private var showChatView = false
    @ObservedObject private var generationManager = SongGenerationManager.shared
    @StateObject private var workspaceManager = WorkspaceManager.shared
    
    var body: some View {
        ZStack {
            // App background color
            Color.black
                .ignoresSafeArea()
                .zIndex(-1)
            
            // Background View - always visible
            backgroundContent
                .zIndex(0)
            
            // Create sheet overlay
            if showCreateSheet {
                Color.black.opacity(0.5)
                    .ignoresSafeArea()
                    .zIndex(1)
            }
            
            // Global Loading Toast - appears on all tabs
            if generationManager.showToast && toastVisible {
                VStack {
                    LoadingToast()
                        .padding(.horizontal, 16)
                        .padding(.top, 8)
                        .onTapGesture {
                            // Open workspace when toast is tapped
                            generationManager.openWorkspace()
                        }
                    Spacer()
                }
                .transition(.move(edge: .top).combined(with: .opacity))
                .animation(.easeOut(duration: 0.4), value: toastVisible)
                .zIndex(2)
            }
        }
        .onChange(of: showCreateSheet) { oldValue, newValue in
            if newValue && !oldValue {
                showChatView = true
                showCreateSheet = false // Reset the binding
            }
        }
        .fullScreenCover(isPresented: $showChatView) {
            ChatView(
                navigationPath: $navigationPath,
                onDismiss: {
                    showChatView = false
                }
            )
        }
        .sheet(isPresented: $generationManager.showWorkspace) {
            WorkspaceView(
                onDismiss: {
                    generationManager.closeWorkspace()
                },
                onTrackTap: { track in
                    print("Track tapped: \(track.title)")
                },
                onEditPrompt: {
                    generationManager.startEditingMode()
                },
                showHeader: true
            )
            .presentationDetents([.large])
            .presentationDragIndicator(.hidden)
            .presentationBackground {
                Color(Constants.Colors.Background.secondary)
            }
        }
        .sheet(isPresented: $generationManager.showCreateSheet) {
            CreateView()
                .presentationDetents([.large])
                .presentationDragIndicator(.hidden)
                .presentationBackground {
                    Color(Constants.Colors.Background.secondary)
                }
        }
        .onChange(of: generationManager.showToast) { _, newValue in
            if newValue {
                // Delay the toast appearance by 0.3s and then slide it in from the top
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                    withAnimation(.easeOut(duration: 0.4)) {
                        toastVisible = true
                    }
                }
            } else {
                // Hide immediately when showToast becomes false
                toastVisible = false
            }
        }
    }
    
    // Background content that stays visible behind the sheet
    private var backgroundContent: some View {
        NavigationStack(path: $navigationPath) {
            ZStack {
                // Background color
                Constants.BackgroundPrimary
                    .ignoresSafeArea()
                
                VStack(spacing: 0) {
                    // Main content area
                    Group {
                        switch selectedTab {
                        case .hooks:
                            HooksView()
                        case .explore:
                            ExploreView()
                        case .library:
                            LibraryTabView()
                        case .profile:
                            ProfileView()
                        }
                    }
                    .frame(maxWidth: .infinity, maxHeight: .infinity)
                    
                    // Bottom Navigation
                    BottomNavBar(selectedTab: $selectedTab, showCreateSheet: $showCreateSheet)
                }
            }
            .navigationDestination(for: MainDestination.self) { destination in
                switch destination {
                case .create:
                    // Chat is now handled by fullScreenCover, but keep case for exhaustiveness
                    EmptyView()

                case .lyricsEditor(let lyrics, let songTitle):
                    EditorView(
                        lyrics: lyrics,
                        songTitle: songTitle,
                        currentTime: "0:20",
                        totalTime: "2:00",
                        progress: 0.167,
                        artworkGradient: LinearGradient(colors: [.orange, .pink], startPoint: .topLeading, endPoint: .bottomTrailing),
                        isPlaying: false,
                        onBackTap: {
                            navigationPath.removeLast()
                        },
                        onPlayPause: {
                            // Handle play/pause
                        },
                        onPlayerExpand: {
                            // Handle player expand
                        },
                        onPlayerClose: {
                            // Handle player close
                        },
                        onSendChatMessage: { message in
                            // Handle send message
                        }
                    )
                    .navigationBarHidden(true)
                    
                case .library:
                    WorkspacesView(
                        onBackTap: {
                            navigationPath.removeLast()
                        },
                        onUploadTap: {
                            print("Upload tapped")
                        },
                        onSearchTap: {
                            print("Search tapped")
                        },
                        onNewWorkspaceTap: {
                            print("New workspace tapped")
                        },
                        onWorkspaceTap: { workspace in
                            navigationPath.append(MainDestination.workspace(
                                workspaceTitle: workspace.name,
                                workspaceImageId: workspace.imageId,
                                chatSongs: []
                            ))
                        },
                        onWorkspaceMenuTap: { workspace in
                            print("Menu tapped for: \(workspace.name)")
                        }
                    )
                    .toolbar(.hidden, for: .navigationBar)
                    
                case .workspaces:
                    WorkspacesView(
                        onBackTap: {
                            navigationPath.removeLast()
                        },
                        onUploadTap: {
                            print("Upload tapped")
                        },
                        onSearchTap: {
                            print("Search tapped")
                        },
                        onNewWorkspaceTap: {
                            print("New workspace tapped")
                        },
                        onWorkspaceTap: { workspace in
                            let workspaceSongs = workspaceManager.getSongsForWorkspace(workspaceId: workspace.id)
                            navigationPath.append(MainDestination.workspace(
                                workspaceTitle: workspace.name,
                                workspaceImageId: workspace.imageId,
                                chatSongs: workspaceSongs
                            ))
                        },
                        onWorkspaceMenuTap: { workspace in
                            print("Menu tapped for: \(workspace.name)")
                        }
                    )
                    
                case .workspace(let workspaceTitle, let workspaceImageId, let chatSongs):
                    WorkspaceView(
                        onDismiss: {
                            navigationPath.removeLast()
                        },
                        onTrackTap: { track in
                            print("Track tapped: \(track.title)")
                        },
                        onEditPrompt: {
                            print("Edit prompt")
                        },
                        workspaceTitle: workspaceTitle,
                        workspaceImageId: workspaceImageId,
                        chatSongs: chatSongs,
                        showBottomBar: false,
                        showHeader: true
                    )
                    .navigationBarHidden(true)
                    
                case .workspaceChat(let workspaceTitle, let workspaceImageId, let chatSongs):
                    WorkspaceView(
                        onDismiss: {
                            navigationPath.removeLast()
                            // Re-show chat sheet when returning from workspace
                            generationManager.showCreateSheet = true
                        },
                        onTrackTap: { track in
                            print("Track tapped: \(track.title)")
                        },
                        onEditPrompt: {
                            print("Edit prompt")
                        },
                        workspaceTitle: workspaceTitle,
                        workspaceImageId: workspaceImageId,
                        chatSongs: chatSongs,
                        showBottomBar: false,
                        showHeader: true
                    )
                    .navigationBarHidden(true)
                    
                case .createView:
                    CreateView()
                        .toolbar(.hidden, for: .navigationBar)
                }
            }
        }
    }
}


// MARK: - Tab Views

struct HooksView: View {
    var body: some View {
        VideoPlayerView()
    }
}

struct ExploreView: View {
    var body: some View {
        NavigationStack {
            ScrollView {
                VStack(spacing: 16) {
                    Text("Discover trending content")
                        .font(Constants.Typography.mediumRegular)
                        .foregroundColor(Constants.ForegroundSecondary)
                        .frame(maxWidth: .infinity, alignment: .leading)

                    // Add your explore content here
                }
                .padding()
            }
            .navigationTitle("Explore")
            .toolbarTitleDisplayMode(.inlineLarge)
            .toolbar {
                ToolbarItem{
                    Button {
                        // Handle filter button action
                        print("Filter button tapped")
                    } label: {
                        Image(systemName: "line.3.horizontal.decrease.circle")
                            .foregroundColor(Constants.ForegroundPrimary)
                    }
                }
                
                ToolbarSpacer()
                
                ToolbarItem{
                    Button {
                        // Handle filter button action
                        print("Filter button tapped")
                    } label: {
                        Image(systemName: "line.3.horizontal.decrease.circle")
                            .foregroundColor(Constants.ForegroundPrimary)
                    }
                }
                
            }
        }
    }
}

struct LibraryTabView: View {
    var body: some View {
        WorkspacesView()
    }
}

// ProfileView moved to ProfileView.swift

#Preview {
    ContentView()
}
