import SwiftUI

struct StyleDescription: View {
    @State private var isExpanded: Bool
    @Binding var styleText: String
    @FocusState private var isTextFieldFocused: Bool
    @State private var showSavedLyricsSheet: Bool = false
    let onSaveStyle: ((String) -> Void)?
    let modelVersion: String
    let startExpanded: Bool
    
    init(styleText: Binding<String> = .constant(""), modelVersion: String = "v4.5", startExpanded: Bool = true, onSaveStyle: ((String) -> Void)? = nil) {
        self._styleText = styleText
        self.modelVersion = modelVersion
        self.startExpanded = startExpanded
        self.onSaveStyle = onSaveStyle
        self._isExpanded = State(initialValue: startExpanded)
    }
    
    // Character limit based on model version
    private var characterLimit: Int {
        modelVersion == "v3.5" ? 200 : 1000
    }
    
    // Show warning threshold (90% of limit)
    private var warningThreshold: Int {
        Int(Double(characterLimit) * 0.9)
    }
    
    private let musicStyles = ["hip hop", "rnb", "pop", "dance", "country"]
    
    // Computed property to determine if we're in typing mode
    private var isTypingMode: Bool {
        !styleText.isEmpty
    }
    
    var body: some View {
        VStack(alignment: .leading, spacing: 0) {
            // Header
            HStack(spacing: 8) {
                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.2), value: isExpanded)
                }
                .buttonStyle(PlainButtonStyle())
                
                VStack(alignment: .leading, spacing: 4) {
                    HStack(alignment: .bottom, spacing: 8) {
                        Text("Style")
                            .font(Constants.Typography.small)
                            .foregroundColor(Constants.Colors.Foreground.primary)
                            .lineLimit(1)
                        
                        // Show character count when approaching limit
                        if styleText.count >= warningThreshold {
                            Text("\(styleText.count)")
                                .font(Constants.Typography.xSmallRegular)
                                .foregroundColor(Constants.Colors.Accent.error)
                        }
                    }
                    
                    // Show typed text preview when collapsed and text exists
                    if !isExpanded && !styleText.isEmpty {
                        Text(styleText)
                            .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) {

                        MediumButton.secondaryIcon("Icon/edit-undo") {
                            withAnimation(.easeInOut(duration: 0.2)) {
                                styleText = ""
                                isTextFieldFocused = false
                            }
                        }

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

                        MediumButton.secondaryIcon("Icon/bookmark-outline") {
                            onSaveStyle?(styleText)
                        }

                        // Generate/Apply button (secondary style)
                        MediumButton.secondaryIcon("Icon/wand") {
                            // Fill with sample style description
                            styleText = "A moody hip-hop beat anchors the track, interwoven with warm R&B chords on electric piano and subtle indie guitar riffs. Lo-fi drum grooves build into lush, layered choruses with atmospheric synths and mellow bass, adding dynamic shifts through stripped-down verses and vibrant vocal hooks."
                        }
                    }
                }
            }
            .padding(.horizontal, 16)
            .frame(height: 64)
            
            if isExpanded {
                // Text input section
                VStack(alignment: .leading, spacing: 0) {
                    ZStack(alignment: .topLeading) {
                        if styleText.isEmpty {
                            VStack(alignment: .leading, spacing: 4) {
                                Text("What do you want your remix to sound like?")
                                Text("(eg: hip-hop, distorted, r&b, female vocals)")
                            }
                            .font(Constants.Typography.mediumRegular)
                            .foregroundColor(Constants.Colors.Background.Fog.dense)
                            .allowsHitTesting(false)
                            .frame(maxHeight: .infinity, alignment: .top)
                        }
                        
                        TextField("", text: $styleText, 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: styleText) { _, newValue in
                                // Enforce character limit based on model version
                                if newValue.count > characterLimit {
                                    styleText = String(newValue.prefix(characterLimit))
                                }
                            }
                    }
                    .frame(minHeight: 60, maxHeight: .infinity, alignment: .top)
                }
                .padding(.horizontal, 16)
                .padding(.bottom, 16)
                
                // Footer section - changes based on typing mode
                if isTypingMode {
                    // Enhanced UI when typing
                    VStack(spacing: 12) {
                        // Quick action buttons
                        ScrollView(.horizontal, showsIndicators: false) {
                            HStack(spacing: 8) {
                                // Library access button
                                MediumButton.secondaryIcon("Icon/library") {
                                    showSavedLyricsSheet = true
                                }
                                
                                // Quick style additions
                                ForEach(musicStyles, id: \.self) { style in
                                    MediumButton.secondary(style, leftIconAssetName: "Icon/plus") {
                                        if styleText.isEmpty {
                                            styleText = style
                                        } else {
                                            styleText += ", " + style
                                        }
                                    }
                                }
                            }
                            .padding(.horizontal, 16)
                        }
                    }
                    .padding(.bottom, 16)
                } else {
                    // Standard UI when not typing
                    ScrollView(.horizontal, showsIndicators: false) {
                        HStack(spacing: 8) {
                            // Library button
                            MediumButton.secondaryIcon("Icon/library") {
                                showSavedLyricsSheet = true
                            }
                            
                            // Style suggestion buttons
                            ForEach(musicStyles, id: \.self) { style in
                                MediumButton(title: style, leftIconAssetName: "Icon/plus") {
                                    if styleText.isEmpty {
                                        styleText = style
                                    } else {
                                        styleText += ", " + style
                                    }
                                }
                            }
                        }
                        .padding(.horizontal, 16)
                    }
                    .padding(.bottom, 16)
                }
            }
        }
        .background(Constants.Colors.Background.Fog.thin)
        .clipShape(RoundedRectangle(cornerRadius: 16))
        .sheet(isPresented: $showSavedLyricsSheet) {
            SavedItemsView.styles { selectedStyle in
                // Just print for now to avoid reactive loops
                print("Selected: \(selectedStyle)")
            }
            .presentationDetents([.medium, .large])
            .presentationDragIndicator(.hidden)
        }
    }
}


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