import SwiftUI

struct ChatsView: View {
    let messages: [ChatMessage]
    let currentlyPlayingSongId: String?
    let currentlySelectedSongId: String?
    let isLoading: Bool
    let onSongPlayPause: (String) -> Void
    let onSongSelect: (String) -> Void
    let onCreateMore: () -> Void
    let onLyricsExpand: () -> Void
    let onLinkTap: ((String) -> Void)?
    let shouldAutoScroll: Bool
    let audioManager: AudioManager?
    
    @State private var isNearBottom: Bool = true
    
    private var filteredMessages: [ChatMessage] {
        filterRepetitiveCreateMoreExchanges(messages)
    }
    
    var body: some View {
        ScrollViewReader { proxy in
            ScrollView(showsIndicators: false) {
                LazyVStack(spacing: 24) {
                    ForEach(filteredMessages) { message in
                        if message.isOutgoing {
                            OutgoingMessage(message: message.content, audioFileName: message.audioFileName)
                        } else {
                            // Check if this is a song generation message
                            if let songData = message.songData {
                                SongGenerationMessage(
                                    message: message.content,
                                    lyrics: songData.lyrics,
                                    songs: songData.songs,
                                    suggestions: [], // Suggestions are handled at ChatView level
                                    currentlyPlayingSongId: currentlyPlayingSongId,
                                    currentlySelectedSongId: currentlySelectedSongId,
                                    isLastSongGeneration: isLastSongGenerationMessage(message),
                                    onSuggestionTap: { _ in }, // Not used here
                                    onPlayPause: { songId in
                                        onSongPlayPause(songId)
                                    },
                                    onSongSelect: { songId in
                                        onSongSelect(songId)
                                    },
                                    onExpand: { index in
                                        print("Expand song \(index)")
                                    },
                                    onLyricsExpand: onLyricsExpand,
                                    onSeeMoreLyrics: {
                                        print("See more lyrics")
                                    },
                                    onCreateMore: {
                                        onCreateMore()
                                    },
                                    onAnimationComplete: {
                                        // Scroll to bottom after animation completes
                                        withAnimation(.easeOut(duration: 0.5)) {
                                            proxy.scrollTo("messagesBottom", anchor: .bottom)
                                        }
                                    },
                                    audioManager: audioManager
                                )
                                .onAppear {
                                    checkMessageVisibility(songData: songData, isVisible: true)
                                }
                                .onDisappear {
                                    checkMessageVisibility(songData: songData, isVisible: false)
                                }
                            } else {
                                IncomingMessage(message: message.content, onLinkTap: onLinkTap)
                            }
                        }
                    }
                    
                    // Show loading message when waiting for response
                    if isLoading {
                        IncomingMessageLoading()
                    }
                    
                    
                    // Invisible element at the very bottom for scrolling
                    Color.clear
                        .frame(height: 220)
                        .id("messagesBottom")
                }
                .padding(.horizontal, 16)
                .padding(.top, 16)
                .onChange(of: messages.count) { _, _ in
                    // Auto-scroll to bottom when new message is added
                    withAnimation(.easeOut(duration: 0.3)) {
                        proxy.scrollTo("messagesBottom", anchor: .bottom)
                    }
                }
                .onChange(of: shouldAutoScroll) { _, shouldScroll in
                    if shouldScroll && isNearBottom {
                        // Auto-scroll to bottom when keyboard appears and user is near end
                        withAnimation(.easeOut(duration: 0.3)) {
                            proxy.scrollTo("messagesBottom", anchor: .bottom)
                        }
                    }
                }
                .background(
                    GeometryReader { geometry in
                        Color.clear
                            .onAppear {
                                // Initial scroll position check
                                updateScrollPosition(geometry: geometry)
                            }
                            .onChange(of: geometry.frame(in: .global)) { _, _ in
                                updateScrollPosition(geometry: geometry)
                            }
                    }
                )
            }
        }
    }
    
    private func checkMessageVisibility(songData: SongResponse, isVisible: Bool) {
        // Check if any song in this message is currently playing
        let hasPlayingSong = songData.songs.contains { song in
            song.id == currentlyPlayingSongId
        }
        
        // No longer need to track playing song visibility since header player is removed
    }
    
    private func isLastSongGenerationMessage(_ message: ChatMessage) -> Bool {
        // Find the last message with song data
        let lastSongMessage = messages.last { $0.songData != nil }
        return message.id == lastSongMessage?.id
    }
    
    private func filterRepetitiveCreateMoreExchanges(_ messages: [ChatMessage]) -> [ChatMessage] {
        // No filtering needed since "create more" no longer generates outgoing messages
        return messages
    }
    
    private func updateScrollPosition(geometry: GeometryProxy) {
        // Check if the scroll view is near the bottom
        let frame = geometry.frame(in: .global)
        let threshold: CGFloat = 100 // Consider "near bottom" if within 100 points
        
        // In a ScrollView, when we're at the bottom, the frame's maxY should be close to the screen height
        let screenHeight = UIScreen.main.bounds.height
        let distanceFromBottom = screenHeight - frame.maxY
        
        let wasNearBottom = isNearBottom
        isNearBottom = distanceFromBottom <= threshold
        
        // Debug logging
        if wasNearBottom != isNearBottom {
            print("📍 Scroll position changed - Near bottom: \(isNearBottom)")
        }
    }
    
    private func isCreateMoreMessage(_ content: String) -> Bool {
        let lowercased = content.lowercased()
        return lowercased.contains("create another version") ||
               lowercased.contains("create more") ||
               lowercased.contains("make another") ||
               lowercased.contains("generate another")
    }
}

struct ChatMessage: Identifiable {
    let id = UUID()
    let content: String
    let isOutgoing: Bool
    let timestamp: Date
    let songData: SongResponse?
    let audioFileName: String?
    
    init(content: String, isOutgoing: Bool, timestamp: Date = Date(), songData: SongResponse? = nil, audioFileName: String? = nil) {
        self.content = content
        self.isOutgoing = isOutgoing
        self.timestamp = timestamp
        self.songData = songData
        self.audioFileName = audioFileName
    }
}

struct ChatsView_Previews: PreviewProvider {
    static var previews: some View {
        let sampleMessages = [
            ChatMessage(content: "I want to make a song about my best friend", isOutgoing: true),
            ChatMessage(content: "Great choice! I'll create an upbeat song about friendship.\nLet me work on some lyrics for you.", isOutgoing: false),
            ChatMessage(content: "Can you make it more emotional and heartfelt?", isOutgoing: true),
            ChatMessage(content: "Here you go, I made two versions of the song.\nLet me know what you want to make edits, I can also\ncreate more versions.", isOutgoing: false),
            ChatMessage(content: "I love the second version! Can you add a bridge section?", isOutgoing: true),
            ChatMessage(content: "Absolutely! Here's the song with an added bridge:\n\nVerse 1:\nWe've been through it all together\nThrough the storms and sunny weather\n\nChorus:\nYou're my best friend, through and through\nThere's nothing that we can't get through\n\nBridge:\nWhen the world gets heavy on my shoulders\nYou remind me that we're getting older\nBut our friendship stays forever young\nThis is our song, and it's just begun", isOutgoing: false)
        ]
        
        ChatsView(
            messages: sampleMessages,
            currentlyPlayingSongId: nil,
            currentlySelectedSongId: nil,
            isLoading: false,
            onSongPlayPause: { songId in
                print("Play/Pause song: \(songId)")
            },
            onSongSelect: { songId in
                print("Select song: \(songId)")
            },
            onCreateMore: {
                print("Create more tapped")
            },
            onLyricsExpand: {
                print("Lyrics expand tapped")
            },
            onLinkTap: { url in
                print("Link tapped: \(url)")
            },
            shouldAutoScroll: false,
            audioManager: nil
        )
        .background(Constants.Colors.Background.primary)
    }
}
