import SwiftUI

struct ChatBar: View {
    @Binding var text: String
    let suggestions: [String]
    let onPlusTap: () -> Void
    let onUploadTap: () -> Void
    let onRecordTap: () -> Void 
    let onLibraryTap: () -> Void
    let onMicrophoneTap: () -> Void
    let onSendTap: () -> Void
    let onSuggestionTap: (String) -> Void
    let placeholder: String
    let scrollToBeginning: Bool
    @Binding var isChatBarFocused: Bool
    let audioFileName: String?
    let uploadProgress: Double
    let isUploading: Bool
    let uploadCompleted: Bool
    let onCloseAudio: () -> Void
    let onPlayPauseSelected: () -> Void
    let currentlyPlayingSongTitle: String?
    let currentArtworkGradient: LinearGradient?
    let isSelectedSongPlaying: Bool
    
    @FocusState private var isTextFieldFocused: Bool
    @State private var forceMultilineLayout: Bool = false
    
    init(
        text: Binding<String>,
        suggestions: [String] = [],
        onPlusTap: @escaping () -> Void = {},
        onUploadTap: @escaping () -> Void = {},
        onRecordTap: @escaping () -> Void = {},
        onLibraryTap: @escaping () -> Void = {},
        onMicrophoneTap: @escaping () -> Void = {},
        onSendTap: @escaping () -> Void = {},
        onSuggestionTap: @escaping (String) -> Void = { _ in },
        placeholder: String = "What do you want to make?",
        scrollToBeginning: Bool = false,
        isChatBarFocused: Binding<Bool>,
        audioFileName: String? = nil,
        uploadProgress: Double = 0.0,
        isUploading: Bool = false,
        uploadCompleted: Bool = false,
        onCloseAudio: @escaping () -> Void = {},
        onPlayPauseSelected: @escaping () -> Void = {},
        currentlyPlayingSongTitle: String? = nil,
        currentArtworkGradient: LinearGradient? = nil,
        isSelectedSongPlaying: Bool = false
    ) {
        self._text = text
        self.suggestions = suggestions
        self.onPlusTap = onPlusTap
        self.onUploadTap = onUploadTap
        self.onRecordTap = onRecordTap
        self.onLibraryTap = onLibraryTap
        self.onMicrophoneTap = onMicrophoneTap
        self.onSendTap = onSendTap
        self.onSuggestionTap = onSuggestionTap
        self.placeholder = placeholder
        self.scrollToBeginning = scrollToBeginning
        self._isChatBarFocused = isChatBarFocused
        self.audioFileName = audioFileName
        self.uploadProgress = uploadProgress
        self.isUploading = isUploading
        self.uploadCompleted = uploadCompleted
        self.onCloseAudio = onCloseAudio
        self.onPlayPauseSelected = onPlayPauseSelected
        self.currentlyPlayingSongTitle = currentlyPlayingSongTitle
        self.currentArtworkGradient = currentArtworkGradient
        self.isSelectedSongPlaying = isSelectedSongPlaying
    }
    
    var body: some View {
        VStack(spacing: 0) {
            
            Rectangle()
                .fill(.clear)
                .frame(height: 16)
            
            if !suggestions.isEmpty {
                suggestionsView
            }
            
            // Audio file display (when present)
            if let audioFileName = audioFileName {
                audioFileView
            }
            
            // Chat input bar with integrated plus button
            integratedInputBar
        }
    }
    
    private var integratedInputBar: some View {
        let shouldUseMultilineLayout = text.count > 32 || forceMultilineLayout
        let cornerRadius: CGFloat = shouldUseMultilineLayout ? 24 : 100
        let minHeight: CGFloat = 56
        
        return HStack(alignment: shouldUseMultilineLayout ? .bottom : .center, spacing: 16) {
            
            // Always show plus button when no audio file present
            if audioFileName == nil {
                integratedPlusButton
            }
            
            if audioFileName != nil {
                Spacer()
                    .frame(width: 0.1)
            }
            
            // Text Input
            adaptiveTextInput
            
            rightButton
        }
        .padding(.horizontal, shouldUseMultilineLayout ? 8 : 8)
        .padding(.vertical, shouldUseMultilineLayout ? 8 : 8)
        .frame(minHeight: minHeight)
        .background(
            RoundedRectangle(cornerRadius: cornerRadius)
                .stroke(Constants.Colors.Border.primary, lineWidth: 1)
        )
        .clipShape(RoundedRectangle(cornerRadius: cornerRadius))
        .animation(.easeInOut(duration: 0.2), value: shouldUseMultilineLayout)
    }
    
    private var adaptiveTextInput: some View {
        let shouldUseMultilineLayout = text.count > 32 || forceMultilineLayout
        let alignment: Alignment = shouldUseMultilineLayout ? .topLeading : .leading
        
        return ZStack(alignment: alignment) {
            if text.isEmpty {
                Text(placeholder)
                    .font(Constants.Typography.mediumTitle)
                    .foregroundColor(Constants.Colors.Foreground.primary.opacity(0.3))
                    .tracking(0.32)
                    .padding(.top, shouldUseMultilineLayout ? 4 : 0)
            }
            
            TextField("", text: $text, axis: .vertical)
                .font(Constants.Typography.mediumTitle)
                .foregroundColor(.white)
                .tracking(0.32)
                .textFieldStyle(PlainTextFieldStyle())
                .focused($isTextFieldFocused)
                .lineLimit(shouldUseMultilineLayout ? 1...4 : 1...1)
                .onChange(of: text) { newValue in
                    // Only focus when text is being added, not when cleared
                    if !newValue.isEmpty {
                        isTextFieldFocused = true
                    }
                    
                    // Reset force multiline if text is empty or becomes short again
                    if newValue.isEmpty || (newValue.count <= 32 && !newValue.contains("\n")) {
                        forceMultilineLayout = false
                    }
                    
                    // Force multiline if user added a newline
                    if newValue.contains("\n") && !forceMultilineLayout {
                        forceMultilineLayout = true
                    }
                }
                .onChange(of: isTextFieldFocused) { isFocused in
                    isChatBarFocused = isFocused
                }
        }
        .frame(minHeight: 24)
    }
    
    private var audioFileView: some View {
        HStack(spacing: 24) {
            
            HStack(spacing: 4){
                Image("Icon/audio-file")
                    .resizable()
                    .renderingMode(.template)
                    .frame(width: 16, height: 16)
                    .foregroundColor(Constants.Colors.Foreground.primary)
                
                Text(audioFileName?.uppercased() ?? "")
                    .font(Constants.Typography.timecode.weight(.medium))
                    .foregroundColor(Constants.Colors.Foreground.primary)
                    .tracking(0.24)
            }
            
            // Progress bar
            if isUploading || uploadCompleted {
                GeometryReader { geometry in
                    ZStack(alignment: .leading) {
                        // Background track
                        RoundedRectangle(cornerRadius: 100)
                            .fill(Color.white.opacity(0.04))
                            .frame(height: 4)
                        
                        // Progress track
                        RoundedRectangle(cornerRadius: 100)
                            .fill(uploadCompleted ? Color.green : Constants.Colors.Accent.brand)
                            .frame(width: geometry.size.width * CGFloat(uploadProgress), height: 4)
                            .animation(.easeInOut(duration: 0.3), value: uploadProgress)
                            .animation(.easeInOut(duration: 0.3), value: uploadCompleted)
                    }
                }
                .frame(height: 4)
                .opacity(uploadCompleted && uploadProgress >= 1.0 ? 0 : 1)
                .animation(.easeOut(duration: 1.0).delay(0.5), value: uploadCompleted)
            } else {
                Spacer()
            }
            
            Button {
                onCloseAudio()
            } label: {
                Image("Icon/close")
                    .resizable()
                    .renderingMode(.template)
                    .frame(width: 16, height: 16)
                    .foregroundColor(Constants.Colors.Foreground.tertiary)
            }
            .buttonStyle(PlainButtonStyle())
        }
        .padding(.vertical, 16)
    }
    
    private var integratedPlusButton: some View {
        Menu {
            Button {
                onLibraryTap()
            } label: {
                Label {
                    Text("Library")
                } icon: {
                    Image("Icon/library")
                        .resizable()
                        .frame(width: 16, height: 16)
                }
            }
            
            Button {
                onRecordTap()
            } label: {
                Label {
                    Text("Record")
                } icon: {
                    Image("Icon/microphone")
                        .resizable()
                        .frame(width: 16, height: 16)
                }
            }
            
            Button {
                onUploadTap()
            } label: {
                Label {
                    Text("Upload")
                } icon: {
                    Image("Icon/upload")
                        .resizable()
                        .frame(width: 16, height: 16)
                }
            }
        } label: {
            ZStack {
                Circle()
                    .fill(Constants.Colors.Background.Fog.thin)
                    .frame(width: 40, height: 40)
                
                Image("Icon/plus")
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                    .frame(width: 16, height: 16)
                    .foregroundColor(Constants.Colors.Foreground.primary)
            }
        }
        .menuStyle(BorderlessButtonMenuStyle())
    }
    
    @ViewBuilder
    private var rightButton: some View {
        if text.isEmpty {
            // Microphone Icon
            Button {
                onMicrophoneTap()
            } label: {
                Image("Icon/microphone")
                    .resizable()
                    .renderingMode(.template)
                    .aspectRatio(contentMode: .fit)
                    .frame(width: 24, height: 24)
                    .foregroundColor(Constants.Colors.Background.Fog.dense)
                    .padding(.trailing, 8)
            }
            .buttonStyle(PlainButtonStyle())
        } else {
            // Send Button using Aura Medium Icon Button
            MediumButton.auraIcon("Icon/arrow-up") {
                onSendTap()
            }
        }
    }
    
    private var suggestionsView: some View {
        ScrollViewReader { proxy in
            ScrollView(.horizontal, showsIndicators: false) {
                HStack(spacing: 8) {
                    // Artwork with play/pause and song title (if available)
                    if let songTitle = currentlyPlayingSongTitle, let gradient = currentArtworkGradient {
                        HStack(spacing: 8) {
                            // Mini artwork with play/pause
                            Button(action: onPlayPauseSelected) {
                                ZStack {
                                    ArtworkShader(gradient: gradient, isAlive: isSelectedSongPlaying)
                                        .frame(width: 28, height: 28)
                                        .cornerRadius(8)
                                    
                                    // Play/Pause icon overlay
                                    Image(isSelectedSongPlaying ? "Icon/pause" : "Icon/play")
                                        .resizable()
                                        .frame(width: 16, height: 16)
                                        .foregroundColor(.white)
                                }
                            }
                            .buttonStyle(PlainButtonStyle())
                            
                            // Song title
                            Text("\(songTitle.uppercased()):")
                                .font(Constants.Typography.timecode)
                                .kerning(0.2)
                                .foregroundColor(Constants.Colors.Foreground.primary)
                                .lineLimit(1)
                        }
                    }
                    
                    // Suggestion pills
                    ForEach(Array(suggestions.prefix(5).enumerated()), id: \.offset) { index, suggestion in
                        Button(action: {
                            onSuggestionTap(suggestion)
                        }) {
                            Text(suggestion.uppercased())
                                .font(Constants.Typography.timecode)
                                .kerning(0.2)
                                .foregroundColor(Constants.Colors.Foreground.primary)
                                .lineLimit(1)
                                .padding(.horizontal, 10)
                                .padding(.vertical, 8)
                                .background(
                                    RoundedRectangle(cornerRadius: 100)
                                        .fill(Constants.Colors.Background.Fog.thin)
                                )
                        }
                        .buttonStyle(PlainButtonStyle())
                        .id(index == 0 ? "first" : "suggestion_\(index)")
                    }
                }
                .padding(.horizontal, 0)
                .padding(.vertical, 12)
            }
            .onChange(of: scrollToBeginning) { shouldScroll in
                if shouldScroll {
                    withAnimation(.easeInOut(duration: 0.3)) {
                        proxy.scrollTo("first", anchor: .leading)
                    }
                }
            }
        }
    }
    
    private func colorForSuggestion(_ suggestion: String, index: Int) -> Color {
        // Check if this is an additive suggestion (starts with +)
        if suggestion.hasPrefix("+") {
            // Additive suggestions use foreground.inactive
            return Constants.Colors.Foreground.inactive
        } else {
            // Regular suggestions use foreground.primary
            return Constants.Colors.Foreground.primary
        }
    }
    
}

#Preview {
    VStack(spacing: 20) {
        // Empty State
        ChatBar(
            text: .constant(""),
            onPlusTap: { print("Plus tapped") },
            onMicrophoneTap: { print("Microphone tapped") },
            onSendTap: { print("Send tapped") },
            onSuggestionTap: { suggestion in print("Suggestion tapped: \(suggestion)") },
            isChatBarFocused: .constant(false)
        )
        
        // With Regular Suggestions State
        ChatBar(
            text: .constant(""),
            suggestions: ["EXTEND", "EDIT LYRICS", "REPLACE SECTION", "CHANGE GENRE", "MAKE SLOWER"],
            onPlusTap: { print("Plus tapped") },
            onMicrophoneTap: { print("Microphone tapped") },
            onSendTap: { print("Send tapped") },
            onSuggestionTap: { suggestion in print("Suggestion tapped: \(suggestion)") },
            isChatBarFocused: .constant(false),
            onPlayPauseSelected: { print("Play/Pause selected song") },
            currentlyPlayingSongTitle: "Song Title (#1)",
            currentArtworkGradient: LinearGradient(
                colors: [Color.blue, Color.purple],
                startPoint: .topLeading,
                endPoint: .bottomTrailing
            ),
            isSelectedSongPlaying: true
        )
        
        // With Genre Suggestions State (+ prefix)
        ChatBar(
            text: .constant(""),
            suggestions: ["+POP", "+ROCK", "+HIP-HOP", "+SYNTHWAVE", "+LO-FI"],
            onPlusTap: { print("Plus tapped") },
            onMicrophoneTap: { print("Microphone tapped") },
            onSendTap: { print("Send tapped") },
            onSuggestionTap: { suggestion in print("Suggestion tapped: \(suggestion)") },
            isChatBarFocused: .constant(false)
        )
        
        // Filled State
        ChatBar(
            text: .constant("Hello world"),
            onPlusTap: { print("Plus tapped") },
            onMicrophoneTap: { print("Microphone tapped") },
            onSendTap: { print("Send tapped") },
            onSuggestionTap: { suggestion in print("Suggestion tapped: \(suggestion)") },
            isChatBarFocused: .constant(false)
        )
        
        Spacer()
    }
    .background(Constants.Colors.Background.primary)
}
