import SwiftUI

struct RemixCoverView: View {
    @State private var showWorkspace = false
    @State private var styleDescription: String = ""
    @State private var lyricsDescription: String = "[chorus]\nLet your mind run free\nLet your mind run free\nYou can just let yourself be free\nYou can just let yourself be free"
    @State private var hasCreatedSong = false
    @State private var isLargeDetent: Bool = false
    @State private var songDescriptionHeight: CGFloat = 180
    @State private var showSaveStyleAlert: Bool = false
    @State private var showSaveLyricsAlert: Bool = false
    @State private var selectedModel: String = "v4.5"
    @State private var showModelSwitchAlert: Bool = false
    @State private var pendingModel: String?
    @State private var isKeyboardVisible: Bool = false
    @ObservedObject private var creditsManager = CreditsManager.shared
    @Environment(\.dismiss) private var dismiss
    @Binding var isPresented: Bool
    
    let originalTrackTitle: String
    let remixType: String
    let onBackTap: () -> Void
    
    init(isPresented: Binding<Bool>, originalTrackTitle: String = "Noctural Appiration", remixType: String = "Cover", onBackTap: @escaping () -> Void = {}) {
        self._isPresented = isPresented
        self.originalTrackTitle = originalTrackTitle
        self.remixType = remixType
        self.onBackTap = onBackTap
    }
    
    var body: some View {
        mainContent
            .sheet(isPresented: $showWorkspace) {
                workspaceSheet
            }
            .preferredColorScheme(.dark)
            .outOfCreditsAlert(isPresented: $creditsManager.showOutOfCreditsAlert) {
                print("Upgrade tapped from RemixCoverView")
            }
            .textInputAlert(
                isPresented: $showSaveStyleAlert,
                title: "Save Style",
                message: "Give your style a name so you can find it later",
                placeholder: "Pop vibes",
                primaryButtonTitle: "Save",
                secondaryButtonTitle: "Cancel",
                onPrimaryAction: { styleName in
                    print("Saving style '\(styleName)' with content: \(styleDescription)")
                },
                onSecondaryAction: {
                    print("Cancelled saving style")
                }
            )
            .textInputAlert(
                isPresented: $showSaveLyricsAlert,
                title: "Save Lyrics",
                message: "Give your lyrics a title so it's easy to remember",
                placeholder: "Lonely road",
                primaryButtonTitle: "Save",
                secondaryButtonTitle: "Cancel",
                onPrimaryAction: { lyricsName in
                    print("Saving lyrics '\(lyricsName)' with content: \(lyricsDescription)")
                },
                onSecondaryAction: {
                    print("Cancelled saving lyrics")
                }
            )
            .overlay(alertOverlay)
    }
    
    private var mainContent: some View {
        GeometryReader { geometry in
            ZStack {
                contentStack
                createFooter
            }
            .onAppear {
                checkDetentSize(geometry.size.height)
            }
            .onReceive(NotificationCenter.default.publisher(for: UIResponder.keyboardWillShowNotification)) { _ in
                isKeyboardVisible = true
            }
            .onReceive(NotificationCenter.default.publisher(for: UIResponder.keyboardWillHideNotification)) { _ in
                isKeyboardVisible = false
            }
            .onChange(of: geometry.size.height) { newHeight in
                checkDetentSize(newHeight)
            }
        }
    }
    
    private var contentStack: some View {
        VStack(spacing: 0) {
            Grabber()
            
            HeaderRemix(
                remixType: remixType,
                onBackTap: {
                    isPresented = false
                    onBackTap()
                },
                onModelChange: { newModel in
                    if newModel == "v3.5" && styleDescription.count > 200 {
                        pendingModel = newModel
                        showModelSwitchAlert = true
                    } else {
                        selectedModel = newModel
                    }
                },
                currentStyleLength: styleDescription.count
            )
            
            if creditsManager.creditCount == 0 {
                OutOfCreditsUpsellBanner {
                    print("Upgrade tapped from upsell banner")
                }
            }
            
            ScrollView {
                VStack(spacing: 16) {
                    if creditsManager.creditCount > 0 {
                        CreateAudioPlayer(songTitle: originalTrackTitle)
                    }
                    
                    StyleDescription(styleText: $styleDescription, modelVersion: selectedModel) { currentStyleText in
                        showSaveStyleAlert = true
                    }
                    
                    LyricsDescription(lyricsText: $lyricsDescription, startExpanded: false) { currentLyricsText in
                        showSaveLyricsAlert = true
                    }
                    
                    AdvancedOptions()
                    
                    Spacer().frame(height: 120)
                }
                .padding(16)
            }
            .frame(maxWidth: .infinity, maxHeight: .infinity)
        }
    }
    
    private var createFooter: some View {
        CreateFooter(
            isVisible: !styleDescription.isEmpty,
            isKeyboardVisible: isKeyboardVisible,
            createButtonTitle: "Create",
            createButtonIcon: "Icon/create"
        ) {
            handleCreateAction()
        }
    }
    
    private var workspaceSheet: some View {
        WorkspaceView(
            onDismiss: {
                showWorkspace = false
            },
            onTrackTap: { track in
                print("Track tapped: \(track.title)")
            },
            onEditPrompt: {
                showWorkspace = false
            }
        )
        .presentationDetents([.large])
        .presentationDragIndicator(.hidden)
        .presentationBackground {
            Constants.Colors.Background.Smoke.dense
                .background(.ultraThinMaterial)
        }
    }
    
    private var alertOverlay: some View {
        Group {
            if showModelSwitchAlert {
                CustomAlert(
                    title: "Switch to v3.5 Model?",
                    message: "v3.5 model only supports up to 200 characters for style descriptions. Your current style (\(styleDescription.count) characters) will be cut off to fit this limit.",
                    primaryButtonTitle: "Switch",
                    secondaryButtonTitle: "Cancel",
                    onPrimaryAction: {
                        if let pending = pendingModel {
                            selectedModel = pending
                            styleDescription = String(styleDescription.prefix(200))
                        }
                        pendingModel = nil
                        showModelSwitchAlert = false
                    },
                    onSecondaryAction: {
                        pendingModel = nil
                        showModelSwitchAlert = false
                    },
                    onDismiss: {
                        pendingModel = nil
                        showModelSwitchAlert = false
                    }
                )
                .transition(.opacity.combined(with: .scale(scale: 0.95)))
                .animation(.easeInOut(duration: 0.2), value: showModelSwitchAlert)
            }
        }
    }
    
    private func handleCreateAction() {
        print("Create remix button tapped")
        
        if !CreditsManager.shared.hasEnoughCredits(50) {
            print("❌ Insufficient credits for remix creation")
            CreditsManager.shared.showOutOfCreditsAlert = true
            return
        }
        
        let songInfo = [
            "isRemix": true,
            "originalTrack": originalTrackTitle,
            "styleDescription": styleDescription,
            "lyricsDescription": lyricsDescription
        ] as [String: Any]
        
        CreditsManager.shared.deductCredits(50)
        hasCreatedSong = true
        showWorkspace = true
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
            NotificationCenter.default.post(name: NSNotification.Name("RemixCreated"), object: nil, userInfo: songInfo)
        }
    }
    
    private func checkDetentSize(_ height: CGFloat) {
        // Detect if we're at large detent (full screen height)
        // Large detent is typically > 700pt on most devices
        let isCurrentlyLarge = height > 700
        
        if isCurrentlyLarge != isLargeDetent {
            isLargeDetent = isCurrentlyLarge
            
            withAnimation(.easeInOut(duration: 0.3)) {
                songDescriptionHeight = isLargeDetent ? 300 : 180
            }
            
            print("📱 Remix sheet detent changed - Height: \(height), Large: \(isLargeDetent), Description Height: \(songDescriptionHeight)")
        }
    }
}

#Preview {
    RemixCoverView(isPresented: .constant(true), remixType: "Cover")
}
