import SwiftUI

struct LyricsDescription: View {
    @State private var isExpanded: Bool = false
    @Binding var lyricsText: String
    @FocusState private var isTextFieldFocused: Bool
    @State private var showSavedLyricsSheet: Bool = false
    @State private var showLyricsEditor: Bool = false
    @State private var showLyricsSelection: Bool = false
    let onSaveLyrics: ((String) -> Void)?
    let startExpanded: Bool
    let placeholderText: String
    let showOnlyUndo: Bool
    let hideFooterControls: Bool
    let customHeight: CGFloat?
    
    // Character limit
    private let characterLimit: Int = 5000
    
    // Show warning threshold (90% of limit)
    private var warningThreshold: Int {
        Int(Double(characterLimit) * 0.9)
    }
    
    // Sample lyrics versions for selection
    private let sampleLyricsVersions = [
        LyricsVersion(
            title: "Version 1",
            lyrics: """
[Verse 1]
Sunrise creeping, through the palm trees high,
Golden sunshine, painting the LA sky.
Santa Ana wind, whispers in my ear,
Another perfect day, banishing all fear.

[Chorus]
Oh, LA weather, you're a sunny dream,
Living in your glow, it would always seem,
Blue skies forever, a perfect scene,
LA weather, you're my sun supreme.

[Verse 2]
Driving down the coast, windows rolled down low,
The ocean breeze, a gentle, salty flow.
Hollywood is humming, with a vibrant sound,
In LA's warm embrace, happiness is found.
"""
        ),
        LyricsVersion(
            title: "Version 2",
            lyrics: """
[Verse 1]
California dreaming, under endless skies,
Golden state of mind, where the spirit flies.
Pacific waves are calling, hear them sing,
In this land of sunshine, we are everything.

[Chorus]
West coast living, it's a state of grace,
Finding our rhythm in this golden place,
Ocean to the mountains, we're free to roam,
California dreaming, this is our home.

[Verse 2]
From the bay to the beach, we're living large,
City lights and starlight, we're in charge.
Every sunset paints a brand new scene,
Living in the moment, chasing every dream.
"""
        ),
        LyricsVersion(
            title: "Version 3",
            lyrics: """
[Verse 1]
Walking through the streets, where the angels play,
In the city of dreams, we'll find our way.
Neon lights are flashing, stories to be told,
In this concrete jungle, hearts are made of gold.

[Chorus]
City of angels, where dreams come true,
Every corner holds something new,
From downtown to the hills so high,
In LA we're reaching for the sky.

[Bridge]
Stars on Hollywood Boulevard,
Dreams that travel near and far,
In this city, we're all stars,
Nothing's gonna keep us apart.
"""
        )
    ]
    
    init(lyricsText: Binding<String> = .constant(""), startExpanded: Bool = true, placeholderText: String = "Write lyrics or leave blank for instrumental", onSaveLyrics: ((String) -> Void)? = nil, showOnlyUndo: Bool = false, hideFooterControls: Bool = false, customHeight: CGFloat? = nil) {
        self._lyricsText = lyricsText
        self.startExpanded = startExpanded
        self.placeholderText = placeholderText
        self.onSaveLyrics = onSaveLyrics
        self.showOnlyUndo = showOnlyUndo
        self.hideFooterControls = hideFooterControls
        self.customHeight = customHeight
        self._isExpanded = State(initialValue: startExpanded)
    }
    
        
    // Computed property to determine if we're in typing mode
    private var isTypingMode: Bool {
        !lyricsText.isEmpty
    }
    
    var body: some View {
        VStack(alignment: .leading, spacing: 0) {
            // Header
            HStack(spacing: 8) {
                if !hideFooterControls {
                    Button(action: {
                        withAnimation(.easeInOut(duration: 0.2)) {
                            isExpanded.toggle()
                        }
                    }) {
                        Image("Icon/chevron-down")
                            .resizable()
                            .aspectRatio(contentMode: .fit)
                            .foregroundColor(Constants.Colors.Foreground.primary)
                            .frame(width: 12, height: 12)
                            .rotationEffect(.degrees(isExpanded ? 0 : -90))
                            .animation(.easeInOut(duration: 0.3), value: isExpanded)
                    }
                    .buttonStyle(PlainButtonStyle())
                }
                
                VStack(alignment: .leading, spacing: 4) {
                    HStack(alignment: .bottom, spacing: 8) {
                        Text("Lyrics")
                            .font(Constants.Typography.small)
                            .foregroundColor(Constants.Colors.Foreground.primary)
                            .lineLimit(1)
                        
                        // Show character count when approaching limit
                        if lyricsText.count >= warningThreshold {
                            Text("\(lyricsText.count)")
                                .font(Constants.Typography.xSmallRegular)
                                .foregroundColor(Constants.Colors.Accent.error)
                        }
                    }
                    
                    // Show typed text preview when collapsed and text exists
                    if !isExpanded && !lyricsText.isEmpty {
                        Text(lyricsText.replacingOccurrences(of: "\n", with: " "))
                            .font(Constants.Typography.xSmallRegular)
                            .foregroundColor(Constants.Colors.Foreground.tertiary)
                            .lineLimit(1)
                            .multilineTextAlignment(.leading)
                    }
                }
                
                Spacer()
                
                // Show action buttons when in typing mode
                if isTypingMode && isExpanded {
                    HStack(spacing: 8) {
                        if showOnlyUndo {
                            // Only show undo button
                            MediumButton.secondaryIcon("Icon/edit-undo") {
                                withAnimation(.easeInOut(duration: 0.2)) {
                                    lyricsText = ""
                                    isTextFieldFocused = false
                                }
                            }
                        } else {
                            // Show all buttons (original behavior)
                            MediumButton.secondaryIcon("Icon/edit-undo") {
                                withAnimation(.easeInOut(duration: 0.2)) {
                                    lyricsText = ""
                                    isTextFieldFocused = false
                                }
                            }

                            MediumButton.secondaryIcon("Icon/clear") {
                                withAnimation(.easeInOut(duration: 0.2)) {
                                    lyricsText = ""
                                    isTextFieldFocused = false
                                }
                            }

                            MediumButton.secondaryIcon("Icon/bookmark-outline") {
                                onSaveLyrics?(lyricsText)
                            }

                            // Generate/Apply button (secondary style)
                            MediumButton.secondaryIcon("Icon/wand") {
                                // Open lyrics selection sheet
                                showLyricsSelection = true
                            }
                        }
                    }
                }
            }
            .padding(.horizontal, 16)
            .frame(height: 64)
            
            if isExpanded {
                // Text input section
                VStack(alignment: .leading, spacing: 0) {
                    ZStack(alignment: .topLeading) {
                        if lyricsText.isEmpty {
                            Text(placeholderText)
                                .font(Constants.Typography.mediumRegular)
                                .foregroundColor(Constants.Colors.Background.Fog.dense)
                                .allowsHitTesting(false)
                                .frame(maxHeight: .infinity, alignment: .top)
                        }
                        
                        Group {
                            if hideFooterControls {
                                // EditorView: No line limit for full editing experience
                                TextField("", text: $lyricsText, axis: .vertical)
                                    .font(Constants.Typography.mediumRegular)
                                    .foregroundColor(Constants.Colors.Foreground.primary)
                                    .textFieldStyle(PlainTextFieldStyle())
                                    .focused($isTextFieldFocused)
                                    .keyboardType(.default)
                                    .colorScheme(.dark)
                                    .frame(maxHeight: .infinity, alignment: .top)
                                    .onChange(of: lyricsText) { _, newValue in
                                        // Enforce character limit
                                        if newValue.count > characterLimit {
                                            lyricsText = String(newValue.prefix(characterLimit))
                                        }
                                    }
                            } else {
                                // Regular form: Limited to 10 lines
                                TextField("", text: $lyricsText, axis: .vertical)
                                    .font(Constants.Typography.mediumRegular)
                                    .foregroundColor(Constants.Colors.Foreground.primary)
                                    .lineLimit(1...10)
                                    .textFieldStyle(PlainTextFieldStyle())
                                    .focused($isTextFieldFocused)
                                    .keyboardType(.default)
                                    .colorScheme(.dark)
                                    .frame(maxHeight: .infinity, alignment: .top)
                                    .onChange(of: lyricsText) { _, newValue in
                                        // Enforce character limit
                                        if newValue.count > characterLimit {
                                            lyricsText = String(newValue.prefix(characterLimit))
                                        }
                                    }
                            }
                        }
                    }
                    .frame(
                        minHeight: customHeight ?? (hideFooterControls ? 200 : 60),
                        maxHeight: customHeight ?? .infinity,
                        alignment: .top
                    )
                }
                .padding(.horizontal, 16)
                .padding(.bottom, 16)
                
                // Footer section - lyrics specific controls
                if !hideFooterControls {
                    HStack(spacing: 8) {
                        // Left side controls
                        HStack(spacing: 8) {
                            // Library button
                            MediumButton.secondaryIcon("Icon/library") {
                                showSavedLyricsSheet = true
                            }
                        }

                        Spacer()

                        // Right side - expand button
                        MediumButton.secondaryIcon("Icon/expand-content") {
                            showLyricsEditor = true
                        }
                    }
                    .padding(.horizontal, 16)
                    .padding(.bottom, 16)
                }
            }
        }
        .background(Constants.Colors.Background.Fog.thin)
        .clipShape(RoundedRectangle(cornerRadius: 16))
        .sheet(isPresented: $showSavedLyricsSheet) {
            SavedItemsView.lyrics { selectedLyrics in
                // Just print for now to avoid reactive loops
                print("Selected: \(selectedLyrics)")
            }
            .presentationDetents([.medium, .large])
            .presentationDragIndicator(.hidden)
        }
        .lyricsEditor(
            lyricsText: $lyricsText,
            isPresented: $showLyricsEditor,
            placeholderText: placeholderText,
            onUndo: {
                // Handle undo action
                print("Undo lyrics")
            },
            onDelete: {
                lyricsText = ""
            },
            onBookmark: {
                onSaveLyrics?(lyricsText)
            },
            onMagicWand: {
                // Handle AI generation
                print("Generate lyrics: \(lyricsText)")
            }
        )
        .lyricsSelectionSheet(
            isPresented: $showLyricsSelection,
            versions: sampleLyricsVersions,
            onVersionSelected: { version in
                lyricsText = version.lyrics
                print("Selected lyrics version: \(version.title)")
            }
        )
    }
}


#Preview {
    @Previewable @State var sampleText = ""
    
    LyricsDescription(lyricsText: $sampleText)
        .padding()
        .background(Color.brown)
}
