import SwiftUI

struct ReplaceView: View {
    let songTitle: String
    let artworkGradient: LinearGradient
    let isPlaying: Bool
    let totalDuration: TimeInterval
    let onPlayPause: () -> Void
    let onDone: (String, String) -> Void // (startTime, endTime)
    let onDismiss: () -> Void
    
    @State private var selectionStart: Double = 0.2 // Default to 20% position
    @State private var selectionEnd: Double = 0.6   // Default to 60% position
    @State private var isAudioPlaying: Bool = false
    
    // Computed properties to get the replace time range
    private var replaceStartTime: String {
        let timeInSeconds = totalDuration * selectionStart
        let minutes = Int(timeInSeconds) / 60
        let seconds = Int(timeInSeconds) % 60
        return String(format: "%d:%02d", minutes, seconds)
    }
    
    private var replaceEndTime: String {
        let timeInSeconds = totalDuration * selectionEnd
        let minutes = Int(timeInSeconds) / 60
        let seconds = Int(timeInSeconds) % 60
        return String(format: "%d:%02d", minutes, seconds)
    }
    
    init(
        songTitle: String = "Nocturnal Apparition",
        artworkGradient: LinearGradient? = nil,
        isPlaying: Bool = false,
        totalDuration: TimeInterval = 180.0, // Default 3 minutes
        onPlayPause: @escaping () -> Void = {},
        onDone: @escaping (String, String) -> Void = { _, _ in },
        onDismiss: @escaping () -> Void = {}
    ) {
        self.songTitle = songTitle
        self.artworkGradient = artworkGradient ?? Self.defaultGradient
        self.isPlaying = isPlaying
        self.totalDuration = totalDuration
        self.onPlayPause = onPlayPause
        self.onDone = onDone
        self.onDismiss = onDismiss
    }
    
    var body: some View {
        VStack(spacing: 0) {
            
            Spacer()
            
            // Main content
            VStack(spacing: 16) {
                // Song info section
                HStack(spacing: 16) {
                    // Mini artwork player
                    Button(action: onPlayPause) {
                        ZStack {
                            ArtworkShader(gradient: artworkGradient, isAlive: true)
                                .frame(width: 40, height: 40)
                                .cornerRadius(12)
                            
                            if isPlaying {
                                Image("Icon/pause")
                                    .resizable()
                                    .frame(width: 16, height: 16)
                                    .foregroundColor(Constants.Colors.Foreground.primary)
                            } else {
                                Image("Icon/play")
                                    .resizable()
                                    .frame(width: 16, height: 16)
                                    .foregroundColor(Constants.Colors.Foreground.primary)
                            }
                        }
                    }
                    .buttonStyle(PlainButtonStyle())
                    
                    // Song title
                    Text(songTitle)
                        .font(Constants.Typography.small)
                        .foregroundColor(Constants.Colors.Foreground.primary)
                        .tracking(0.28)
                    
                    Spacer()
                }
                
                // Audio trimmer section
                VStack(spacing: 16) {
                    // Audio waveform with trimmer
                    AudioTrimmer(
                        selectionStart: $selectionStart,
                        selectionEnd: $selectionEnd,
                        isPlaying: $isAudioPlaying,
                        totalDuration: totalDuration,
                        onSelectionChanged: { start, end in
                            print("Replace selection: \(replaceStartTime) - \(replaceEndTime)")
                        }
                    )
                    .frame(height: 80)
                    
                    // Replace info text
                    Text("Replace from \(replaceStartTime) - \(replaceEndTime)")
                        .font(Constants.Typography.xSmallRegular)
                        .foregroundColor(Constants.Colors.Foreground.primary.opacity(0.3))
                        .tracking(0.24)
                }
            }
            .padding(.horizontal, 16)
            .padding(.vertical, 16)
            
            Spacer()
            
            // Footer with Done button
            LargeButton(
                title: "Done",
                variant: .primary,
                action: {
                    onDone(replaceStartTime, replaceEndTime)
                }
            )
            .padding(.horizontal, 16)
            .padding(.vertical, 12)
        }
        .background(Constants.Colors.Background.secondary)
        .onAppear {
            // Sync the audio playing state
            isAudioPlaying = isPlaying
        }
        .onChange(of: isPlaying) { _, newValue in
            isAudioPlaying = newValue
        }
    }
    
    private static var defaultGradient: LinearGradient {
        LinearGradient(
            colors: [
                Color(red: 0.8, green: 0.4, blue: 0.9),
                Color(red: 0.4, green: 0.6, blue: 1.0)
            ],
            startPoint: .topLeading,
            endPoint: .bottomTrailing
        )
    }
}

#Preview {
    let sampleGradient = LinearGradient(
        colors: [
            Color(red: 0.8, green: 0.4, blue: 0.9),
            Color(red: 0.4, green: 0.6, blue: 1.0)
        ],
        startPoint: .topLeading,
        endPoint: .bottomTrailing
    )
    
    ZStack {
        Constants.Colors.Background.primary
            .ignoresSafeArea()
        
        VStack {
            Spacer()
            
            ReplaceView(
                songTitle: "Nocturnal Apparition",
                artworkGradient: sampleGradient,
                isPlaying: true,
                totalDuration: 180.0, // 3 minutes
                onPlayPause: {
                    print("Play/Pause tapped")
                },
                onDone: { startTime, endTime in
                    print("Done tapped - Replace time: \(startTime) - \(endTime)")
                },
                onDismiss: {
                    print("Dismiss tapped")
                }
            )
            .padding(.horizontal, 16)
        }
    }
}