import SwiftUI

struct LyricsEditorView: View {
    @Binding var lyricsText: String
    @Binding var isPresented: Bool
    @FocusState private var isTextFieldFocused: Bool
    
    let placeholderText: String
    let onUndo: (() -> Void)?
    let onDelete: (() -> Void)?
    let onBookmark: (() -> Void)?
    let onMagicWand: (() -> Void)?
    
    init(
        lyricsText: Binding<String>,
        isPresented: Binding<Bool>,
        placeholderText: String = "Write lyrics or prompt",
        onUndo: (() -> Void)? = nil,
        onDelete: (() -> Void)? = nil,
        onBookmark: (() -> Void)? = nil,
        onMagicWand: (() -> Void)? = nil
    ) {
        self._lyricsText = lyricsText
        self._isPresented = isPresented
        self.placeholderText = placeholderText
        self.onUndo = onUndo
        self.onDelete = onDelete
        self.onBookmark = onBookmark
        self.onMagicWand = onMagicWand
    }
    
    var body: some View {
        VStack(spacing: 0) {
            // Drag Handle Header
            VStack(spacing: 12) {
                // Drag handle
                RoundedRectangle(cornerRadius: 100)
                    .fill(Constants.Colors.Background.Fog.thick)
                    .frame(width: 32, height: 4)
            }
            .frame(height: 16)
            .padding(.top, 16)
            
            // Action Buttons Toolbar
            HStack(spacing: 8) {
                Spacer()
                
                HStack(spacing: 8) {
                    // Undo Button
                    MediumButton.secondaryIcon("Icon/edit-undo") {
                        onUndo?()
                    }
                    
                    // Delete Button
                    MediumButton.secondaryIcon("Icon/clear") {
                        onDelete?()
                    }
                    
                    // Bookmark Button
                    MediumButton.secondaryIcon("Icon/bookmark-outline") {
                        onBookmark?()
                    }
                    
                    // Magic Wand Button (with aura style)
                    MediumButton.auraIcon("Icon/wand") {
                        onMagicWand?()
                    }
                }
            }
            .padding(.horizontal, 16)
            .frame(height: 72)
            
            // Text Editor Area
            ZStack {
                ScrollView {
                    VStack(alignment: .leading, spacing: 0) {
                        ZStack(alignment: .topLeading) {
                            // Placeholder text
                            if lyricsText.isEmpty {
                                HStack {
                                    Text(placeholderText)
                                        .font(Constants.Typography.mediumRegular)
                                        .foregroundColor(Constants.Colors.Foreground.tertiary)
                                        .tracking(0.32)
                                    Spacer()
                                }
                                .padding(.top, 4)
                            }
                            
                            // Text Editor
                            TextField("", text: $lyricsText, axis: .vertical)
                                .font(Constants.Typography.mediumRegular)
                                .foregroundColor(Constants.Colors.Foreground.primary)
                                .tracking(0.32)
                                .lineSpacing(8)
                                .textFieldStyle(PlainTextFieldStyle())
                                .focused($isTextFieldFocused)
                                .keyboardType(.default)
                                .frame(minHeight: 200, alignment: .topLeading)
                        }
                        .padding(.top, 4)
                    }
                    .padding(.horizontal, 16)
                }
                
                // Collapse Button (positioned at bottom right)
                VStack {
                    Spacer()
                    HStack {
                        Spacer()
                        
                        Button(action: {
                            withAnimation(.easeInOut(duration: 0.3)) {
                                isPresented = false
                            }
                        }) {
                            Image("Icon/collapse-content")
                                .resizable()
                                .renderingMode(.template)
                                .foregroundColor(Constants.Colors.Background.primary)
                                .frame(width: 14, height: 14)
                        }
                        .buttonStyle(PlainButtonStyle())
                        .frame(width: 40, height: 40)
                        .background(Constants.Colors.Foreground.primary)
                        .clipShape(RoundedRectangle(cornerRadius: 100))
                        .padding(.trailing, 16)
                        .padding(.bottom, 16)
                    }
                }
            }
            .frame(maxWidth: .infinity, maxHeight: .infinity)
        }
        .background(Constants.Colors.Background.secondary)
        .clipShape(
            RoundedRectangle(cornerRadius: 24)
        )
        .onAppear {
            isTextFieldFocused = true
        }
    }
}

// MARK: - Convenience View Modifier
extension View {
    func lyricsEditor(
        lyricsText: Binding<String>,
        isPresented: Binding<Bool>,
        placeholderText: String = "Write lyrics or prompt",
        onUndo: (() -> Void)? = nil,
        onDelete: (() -> Void)? = nil,
        onBookmark: (() -> Void)? = nil,
        onMagicWand: (() -> Void)? = nil
    ) -> some View {
        self.sheet(isPresented: isPresented) {
            LyricsEditorView(
                lyricsText: lyricsText,
                isPresented: isPresented,
                placeholderText: placeholderText,
                onUndo: onUndo,
                onDelete: onDelete,
                onBookmark: onBookmark,
                onMagicWand: onMagicWand
            )
            .presentationDetents([.large])
            .presentationDragIndicator(.hidden)
            .presentationCornerRadius(24)
        }
    }
}

// MARK: - Preview
#Preview {
    @Previewable @State var lyricsText = "[Verse 1]\nSunrise creeping, through the palm trees high,\nGolden sunshine, painting the LA sky,\nSanta Ana wind, whispers in my ear,\nAnother perfect day, banishing all fear.\n\n[Chorus]\nOh, LA weather, you're a sunny dream,\nLiving in your glow, it would always seem,\nBlue skies forever, a perfect scene,\nLA weather, you're my sun supreme.\n\n[Verse 2]\nDriving down the coast, windows rolled down low,\nThe ocean breeze, a gentle, salty flow,\nHollywood is humming, with a vibrant sound,\nIn LA's warm embrace, happiness is found."
    @Previewable @State var isPresented = true
    
    Color.clear
        .lyricsEditor(
            lyricsText: $lyricsText,
            isPresented: $isPresented,
            onUndo: { print("Undo tapped") },
            onDelete: { lyricsText = "" },
            onBookmark: { print("Bookmark tapped") },
            onMagicWand: { print("Magic wand tapped") }
        )
}
