import SwiftUI
import Combine

struct EmptyChat: View {
    let onUploadTap: () -> Void
    let onRecordTap: () -> Void
    let onWriteLyricsTap: () -> Void
    let onSwitchToCustomTap: () -> Void
    let onSuggestionTap: ((String) -> Void)?
    
    @State private var currentTextIndex: Int = 0
    @State private var displayedText: String = ""
    @State private var isTyping: Bool = false
    @State private var isKeyboardVisible: Bool = false
    @State private var scrollOffset: CGFloat = 0
    @State private var hasReachedThreshold: Bool = false
    @State private var scrollPosition: CGPoint = .zero
    
    private let pullThreshold: CGFloat = -80 // Distance to pull up before changing text
    
    // Calculate arrow scale based on scroll progress (1.0 to 1.8)
    private var arrowScale: Double {
        // Clamp scroll offset between 0 and pullThreshold
        let progress = min(max(scrollOffset / pullThreshold, 0), 1)
        // Scale from 1.0 to 1.8 based on progress
        return 1.0 + (progress * 0.2)
    }
    
    
    private let textOptions = [
        "Make any song you can imagine",
        "Make a jazz song about watering my plants",
        "Make a house song about quitting your job",
        "Make a country song about Jess being late"
    ]
    
    var body: some View {
        ScrollView {
            VStack(spacing: 24) {
                Spacer()
                    .frame(height: 80)

                VStack(spacing: 8) {

                    if !isKeyboardVisible {
                        titleSection
                    }

                    actionCardsSection
                        .id("middle-content")

                    // Switch to custom button
                    switchToCustomButton

                    // Suggestions list
                    if let onSuggestionTap = onSuggestionTap {
                        SuggestionsList(
                            onSuggestionTap: onSuggestionTap,
                            onShuffleTap: {
                                // The SuggestionsList component handles shuffling internally
                            }
                        )
                        .padding(.top, 16)
                    }
                }
                .padding(.horizontal, 16)


                Spacer()
                    .frame(height: 120)
            }
        }
        .onAppear {
            startTypingAnimation()
            setupKeyboardObservers()
        }
    }
    
    private var titleSection: some View {
        Text(attributedString)
            .lineLimit(3)
            .multilineTextAlignment(.center)
            .fixedSize(horizontal: false, vertical: true)
            .frame(minHeight: 80) // Consistent height for text transitions
    }
    
    private var attributedString: AttributedString {
        var text = AttributedString(displayedText)
        text.font = .custom("PP Neue Montreal", size: 28).weight(.medium)
        text.foregroundColor = .white
        text.tracking = 0.56
        
        // Add static cursor at the end
        var cursor = AttributedString("|")
        cursor.font = .custom("PP Neue Montreal", size: 28).weight(.medium)
        cursor.foregroundColor = Constants.Colors.Foreground.primary
        cursor.tracking = 0.56
        text.append(cursor)
        
        return text
    }
    
    private var actionCardsSection: some View {
        HStack(spacing: 8) {
            // Upload audio card
            ActionCard(
                icon: "Icon/upload",
                title: "Upload audio",
                action: onUploadTap
            )
            
            // Record audio card
            ActionCard(
                icon: "Icon/microphone",
                title: "Record audio",
                action: onRecordTap
            )
            
            // Write lyrics card
            ActionCard(
                icon: "Icon/library",
                title: "Library",
                action: onWriteLyricsTap
            )
        }
    }
    
    private var switchToCustomButton: some View {
        Button {
            onSwitchToCustomTap()
        } label: {
            Text("Open Custom Mode")
                .font(Constants.Typography.small)
                .foregroundColor(Constants.Colors.Foreground.tertiary)
                .tracking(0.28)
        }
        .buttonStyle(PlainButtonStyle())
        .frame(maxWidth: .infinity)
        .frame(height: 56)
        .background(
            RoundedRectangle(cornerRadius: 16)
                .fill(Constants.Colors.Background.Fog.thin)
        )
    }
    
    
    private func startTypingAnimation() {
        typeText()
    }
    
    private func setupKeyboardObservers() {
        NotificationCenter.default.addObserver(
            forName: UIResponder.keyboardWillShowNotification,
            object: nil,
            queue: .main
        ) { _ in
            withAnimation(.easeInOut(duration: 0.3)) {
                isKeyboardVisible = true
            }
        }
        
        NotificationCenter.default.addObserver(
            forName: UIResponder.keyboardWillHideNotification,
            object: nil,
            queue: .main
        ) { _ in
            withAnimation(.easeInOut(duration: 0.3)) {
                isKeyboardVisible = false
            }
        }
    }
    
    
    private func typeText() {
        let currentText = textOptions[currentTextIndex]
        displayedText = ""
        isTyping = true
        
        // Type out the current text
        for (index, character) in currentText.enumerated() {
            DispatchQueue.main.asyncAfter(deadline: .now() + Double(index) * 0.025) {
                displayedText.append(character)
                
                // If this is the last character
                if index == currentText.count - 1 {
                    isTyping = false
                    // Wait 3 seconds before starting to delete
                    DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {
                        deleteText()
                    }
                }
            }
        }
    }
    
    private func deleteText() {
        let currentText = displayedText
        
        // Delete the text character by character
        for index in 0..<currentText.count {
            DispatchQueue.main.asyncAfter(deadline: .now() + Double(index) * 0.015) {
                displayedText = String(currentText.dropLast(index + 1))
                
                // If this is the last character to delete
                if index == currentText.count - 1 {
                    // Move to next text and start typing again
                    currentTextIndex = (currentTextIndex + 1) % textOptions.count
                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                        typeText()
                    }
                }
            }
        }
    }
}

struct ActionCard: View {
    let icon: String
    let title: String
    let action: () -> Void
    
    var body: some View {
        Button {
            action()
        } label: {
            VStack(spacing: 8) {
                Image(icon)
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                    .frame(width: 24, height: 24)
                    .foregroundColor(.white.opacity(0.3))
                
                Text(title)
                    .font(Constants.Typography.small)
                    .foregroundColor(Constants.Colors.Foreground.tertiary)
                    .tracking(0.28)
                    .multilineTextAlignment(.center)
            }
            .frame(maxWidth: .infinity)
            .frame(height: 100)
        }
        .buttonStyle(PlainButtonStyle())
        .background(
            RoundedRectangle(cornerRadius: 20)
                .fill(Constants.Colors.Background.Fog.thin)
        )
    }
}

#Preview {
    EmptyChat(
        onUploadTap: { print("Upload tapped") },
        onRecordTap: { print("Record tapped") },
        onWriteLyricsTap: { print("Write lyrics tapped") },
        onSwitchToCustomTap: { print("Switch to custom tapped") },
        onSuggestionTap: { suggestion in print("Suggestion tapped: \(suggestion)") }
    )
    .background(Constants.Colors.Background.primary)
    .frame(maxWidth: .infinity, maxHeight: .infinity)
}
