import SwiftUI

struct RightHandleAudioTrimmer: View {
    @Binding var selectionEnd: Double   // 0.0 to 1.0 - only this is adjustable
    @State private var isDraggingEndHandle = false
    @State private var originalSelectionEnd: Double = 0
    
    let onSelectionChanged: ((Double) -> Void)?
    let totalDuration: TimeInterval // Total audio duration in seconds
    
    // Sample waveform data - heights normalized to 0.0-1.0
    private let waveformData: [Double] = [
        0.28, 0.47, 0.22, 0.19, 0.67, 0.87, 0.38, 0.76, 0.09, 0.49, 0.18, 0.66, 0.99, 0.38, 0.46, 0.24,
        0.96, 0.27, 0.37, 0.52, 0.73, 0.93, 0.94, 0.32, 0.68, 0.93, 0.24, 0.01, 0.58, 0.75, 0.29, 0.33,
        0.72, 0.57, 0.43, 0.79, 0.02, 0.42, 0.52, 0.55, 0.72, 0.88, 0.59, 0.14, 0.57, 0.92, 0.58, 0.52,
        0.88, 0.53, 0.67, 0.47, 0.59, 0.09, 0.94, 0.80, 0.01, 0.79, 0.31, 0.97, 0.91, 0.46, 0.87, 0.03,
        0.04, 0.98, 0.29, 0.03, 0.58, 0.37, 0.83, 0.46, 0.82, 0.80, 0.53, 0.82, 0.14, 0.55, 0.75, 0.35,
        0.62, 0.03, 0.91, 0.52, 0.04, 0.55, 0.99, 0.54, 0.17, 0.99, 0.35, 0.54, 0.91, 0.54, 0.06, 0.70,
        0.33, 0.57, 0.27, 0.40, 0.47, 0.29, 0.85, 0.44, 0.20, 0.97, 0.57, 0.68, 0.20, 0.47, 0.01, 0.48,
        0.43, 0.59, 0.24, 0.73, 0.72, 0.32, 0.85, 0.47, 0.69, 0.73, 0.42, 0.63, 0.33, 0.39, 0.24, 0.98
    ]
    
    init(
        selectionEnd: Binding<Double>,
        totalDuration: TimeInterval = 180.0, // Default 3 minutes
        onSelectionChanged: ((Double) -> Void)? = nil
    ) {
        self._selectionEnd = selectionEnd
        self.totalDuration = totalDuration
        self.onSelectionChanged = onSelectionChanged
    }
    
    // Helper function to format time duration
    private func formatTime(_ seconds: TimeInterval) -> String {
        let minutes = Int(seconds) / 60
        let remainingSeconds = Int(seconds) % 60
        return String(format: "%d:%02d", minutes, remainingSeconds)
    }
    
    var body: some View {
        GeometryReader { geometry in
            let cornerRadius = min(geometry.size.width * 0.03, 12) // Responsive corner radius
            let padding = max(geometry.size.width * 0.04, 12) // Responsive padding
            let maxWaveHeight: CGFloat = 48 // Fixed max height
            let minWaveHeight: CGFloat = 8 // Fixed min height  
            let barWidth: CGFloat = 3 // Fixed bar width
            let spacing: CGFloat = 3 // Fixed spacing
            
            // Calculate available width and how many bars we can show
            let availableWidth = geometry.size.width - (padding * 2)
            let totalBarAndSpacingWidth = barWidth + spacing
            let maxBars = max(0, Int(availableWidth / totalBarAndSpacingWidth))
            let visibleWaveformData = Array(waveformData.prefix(maxBars))
            
            ZStack {
                // Background with rounded corners
                RoundedRectangle(cornerRadius: cornerRadius)
                    .fill(Color.clear)
                    .overlay(
                        RoundedRectangle(cornerRadius: cornerRadius)
                            .stroke(Constants.Colors.Border.primary, lineWidth: 1)
                    )
                
                // Waveform visualization
                HStack(spacing: spacing) {
                    ForEach(Array(visibleWaveformData.enumerated()), id: \.offset) { index, amplitude in
                        // Calculate the position of this bar within the full container width
                        let barPositionInWaveform = Double(index) / Double(visibleWaveformData.count)
                        let waveformStart = Double(padding) / Double(geometry.size.width)
                        let waveformEnd = Double(geometry.size.width - padding) / Double(geometry.size.width)
                        let waveformWidth = waveformEnd - waveformStart
                        let barPositionInContainer = waveformStart + (barPositionInWaveform * waveformWidth)
                        
                        // Highlight bars from start (0.0) to selectionEnd
                        let isInSelection = barPositionInContainer <= selectionEnd
                        
                        RoundedRectangle(cornerRadius: 100)
                            .fill(isInSelection ? Constants.Colors.Foreground.primary : Constants.Colors.Foreground.primary.opacity(0.3))
                            .frame(width: barWidth, height: max(minWaveHeight, amplitude * maxWaveHeight))
                    }
                }
                .padding(padding)
                
                // Selection overlay - only right handle
                selectionOverlay(geometry: geometry, padding: padding)
                
                // Tooltip for right handle
                tooltipOverlay(geometry: geometry, padding: padding)
            }
        }
        .frame(height: 80)
    }
    
    @ViewBuilder
    private func selectionOverlay(geometry: GeometryProxy, padding: CGFloat) -> some View {
        let totalWidth = geometry.size.width
        let selectionWidth = selectionEnd * totalWidth // Selection from 0.0 to selectionEnd
        let handleWidth: CGFloat = 12 // Fixed handle width
        
        ZStack {
            // Selection background (from start to selectionEnd)
            UnevenRoundedRectangle(
                topLeadingRadius: 12,
                bottomLeadingRadius: 12,
                bottomTrailingRadius: 0,
                topTrailingRadius: 0
            )
            .fill(Constants.Colors.Accent.brand.opacity(0.1))
            .frame(width: selectionWidth, height: geometry.size.height)
            .position(x: selectionWidth/2, y: geometry.size.height/2)
            
            // Right handle only
            UnevenRoundedRectangle(
                topLeadingRadius: 0,
                bottomLeadingRadius: 0,
                bottomTrailingRadius: 4,
                topTrailingRadius: 4
            )
            .fill(Constants.Colors.Accent.brand)
            .frame(width: handleWidth, height: geometry.size.height + 1)
            .position(x: selectionWidth, y: geometry.size.height/2)
            .gesture(
                DragGesture()
                    .onChanged { value in
                        if !isDraggingEndHandle {
                            isDraggingEndHandle = true
                            originalSelectionEnd = selectionEnd
                        }
                        
                        let translation = value.translation.width / totalWidth
                        let newEnd = min(1.0, max(0.05, originalSelectionEnd + translation)) // Minimum 5% selection
                        
                        selectionEnd = newEnd
                        onSelectionChanged?(selectionEnd)
                    }
                    .onEnded { _ in
                        isDraggingEndHandle = false
                    }
            )
        }
        .overlay(
            // Selection border (from start to selectionEnd)
            UnevenRoundedRectangle(
                topLeadingRadius: 12,
                bottomLeadingRadius: 12,
                bottomTrailingRadius: 0,
                topTrailingRadius: 0
            )
            .stroke(Constants.Colors.Accent.brand, lineWidth: 1)
            .frame(width: selectionWidth, height: geometry.size.height)
            .position(x: selectionWidth/2, y: geometry.size.height/2)
        )
    }
    
    @ViewBuilder
    private func tooltipOverlay(geometry: GeometryProxy, padding: CGFloat) -> some View {
        let totalWidth = geometry.size.width
        let selectionWidth = selectionEnd * totalWidth
        
        // Right handle tooltip
        if isDraggingEndHandle {
            let endTime = selectionEnd * totalDuration
            TooltipView(text: formatTime(endTime))
                .position(x: selectionWidth, y: -20) // 20pt above the handle
        }
    }
}

// MARK: - Preview
#Preview {
    @Previewable @State var end: Double = 0.6
    
    VStack(spacing: 20) {
        RightHandleAudioTrimmer(
            selectionEnd: $end,
            totalDuration: 240.0, // 4 minute sample audio
            onSelectionChanged: { newEnd in
                print("Selection end changed: \(newEnd)")
            }
        )
        
        VStack(alignment: .leading, spacing: 8) {
            Text("Selection: 0.00 - \(String(format: "%.2f", end))")
                .font(Constants.Typography.small)
                .foregroundColor(Constants.Colors.Foreground.primary)
            
            Text("Duration: \(String(format: "%.2f", end)) (\(String(format: "%.1f", end * 100))%)")
                .font(Constants.Typography.xSmallRegular)
                .foregroundColor(Constants.Colors.Foreground.tertiary)
        }
    }
    .padding()
    .background(Constants.Colors.Background.primary)
}