import SwiftUI

struct LyricsVersion: Identifiable {
    let id = UUID()
    let title: String
    let lyrics: String
    
    init(title: String, lyrics: String) {
        self.title = title
        self.lyrics = lyrics
    }
}

struct LyricsSelectionView: View {
    @Binding var isPresented: Bool
    @State private var currentVersionIndex: Int = 0
    
    let versions: [LyricsVersion]
    let onVersionSelected: ((LyricsVersion) -> Void)?
    
    init(
        isPresented: Binding<Bool>,
        versions: [LyricsVersion],
        onVersionSelected: ((LyricsVersion) -> Void)? = nil
    ) {
        self._isPresented = isPresented
        self.versions = versions
        self.onVersionSelected = onVersionSelected
    }
    
    private var currentVersion: LyricsVersion? {
        guard currentVersionIndex < versions.count else { return nil }
        return versions[currentVersionIndex]
    }
    
    private var hasPrevious: Bool {
        currentVersionIndex > 0
    }
    
    private var hasNext: Bool {
        currentVersionIndex < versions.count - 1
    }
    
    var body: some View {
        VStack(spacing: 0) {
            // Drag Handle
            VStack(spacing: 12) {
                RoundedRectangle(cornerRadius: 100)
                    .fill(Constants.Colors.Background.Fog.thick)
                    .frame(width: 32, height: 4)
            }
            .frame(height: 16)
            .padding(.top, 16)
            
            // Content
            VStack(spacing: 0) {
                // Version Content
                VStack(alignment: .leading, spacing: 16) {
                    // Version Title
                    if let version = currentVersion {
                        Text(version.title)
                            .font(Constants.Typography.largeTitle)
                            .foregroundColor(Constants.Colors.Foreground.primary)
                            .tracking(0.36)
                            .frame(maxWidth: .infinity, alignment: .leading)
                    }
                    
                    // Lyrics Text
                    ScrollView {
                        VStack(alignment: .leading, spacing: 0) {
                            if let version = currentVersion {
                                Text(version.lyrics)
                                    .font(Constants.Typography.small)
                                    .foregroundColor(Constants.Colors.Foreground.tertiary)
                                    .tracking(0.28)
                                    .lineSpacing(4)
                                    .multilineTextAlignment(.leading)
                                    .frame(maxWidth: .infinity, alignment: .leading)
                            }
                        }
                    }
                }
                .padding(.horizontal, 24)
                .padding(.top, 24)
                .padding(.bottom, 24)
                
                // Navigation and Select Buttons
                HStack(spacing: 9) {
                    // Previous Button
                    Button(action: {
                        withAnimation(.easeInOut(duration: 0.2)) {
                            if hasPrevious {
                                currentVersionIndex -= 1
                            }
                        }
                    }) {
                        Image("Icon/chevron-left")
                            .resizable()
                            .renderingMode(.template)
                            .foregroundColor(Constants.Colors.Foreground.primary)
                            .frame(width: 16, height: 16)
                    }
                    .frame(width: 56, height: 56)
                    .background(
                        Constants.Colors.Background.tertiary
                    )
                    .opacity(hasPrevious ? 1.0 : 0.5)
                    .clipShape(RoundedRectangle(cornerRadius: 100))
                    .disabled(!hasPrevious)
                    
                    // Select Button
                    LargeButton(
                        title: "Select this version",
                        variant: .primary
                    ) {
                        if let version = currentVersion {
                            onVersionSelected?(version)
                            isPresented = false
                        }
                    }
                    
                    // Next Button
                    Button(action: {
                        withAnimation(.easeInOut(duration: 0.2)) {
                            if hasNext {
                                currentVersionIndex += 1
                            }
                        }
                    }) {
                        Image("Icon/chevron-right")
                            .resizable()
                            .renderingMode(.template)
                            .foregroundColor(Constants.Colors.Foreground.primary)
                            .frame(width: 16, height: 16)
                    }
                    .frame(width: 56, height: 56)
                    .background(
                        Constants.Colors.Background.tertiary
                    )
                    .opacity(hasNext ? 1.0 : 0.5)
                    .clipShape(RoundedRectangle(cornerRadius: 100))
                    .disabled(!hasNext)
                }
                .padding(.horizontal, 24)
                .padding(.bottom, 50)
            }
        }
        .background(Constants.Colors.Background.secondary)
        .ignoresSafeArea(.container, edges: .bottom)
    }
}

// MARK: - Convenience View Modifier
extension View {
    func lyricsSelectionSheet(
        isPresented: Binding<Bool>,
        versions: [LyricsVersion],
        onVersionSelected: ((LyricsVersion) -> Void)? = nil
    ) -> some View {
        self.sheet(isPresented: isPresented) {
            LyricsSelectionView(
                isPresented: isPresented,
                versions: versions,
                onVersionSelected: onVersionSelected
            )
            .presentationDetents([.large])
            .presentationDragIndicator(.hidden)
            .presentationCornerRadius(24)
        }
    }
}

// MARK: - Preview
#Preview {
    @Previewable @State var isPresented = true
    
    let sampleVersions = [
        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.
"""
        )
    ]
    
    Color.clear
        .lyricsSelectionSheet(
            isPresented: $isPresented,
            versions: sampleVersions,
            onVersionSelected: { version in
                print("Selected version: \(version.title)")
            }
        )
}
