import SwiftUI

struct AudioTrimmerSelectionView: View {
    @State private var selectionStart: Double = 0.0
    @State private var selectionEnd: Double = 0.4
    @State private var isPlaying: Bool = false
    @State private var title: String = "Untitled"
    @State private var showTitleEditor: Bool = false
    @Binding var isPresented: Bool
    
    let totalDuration: TimeInterval // Total audio duration
    let currentPosition: TimeInterval // Current playback position
    let onCancel: () -> Void
    let onContinue: (Double, Double) -> Void // Returns start and end times in seconds
    
    init(
        isPresented: Binding<Bool>,
        totalDuration: TimeInterval = 120.0, // Default 2 minutes
        currentPosition: TimeInterval = 10.0, // Default 10 seconds
        onCancel: @escaping () -> Void = {},
        onContinue: @escaping (Double, Double) -> Void = { _, _ in }
    ) {
        self._isPresented = isPresented
        self.totalDuration = totalDuration
        self.currentPosition = currentPosition
        self.onCancel = onCancel
        self.onContinue = onContinue
    }
    
    // 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)
    }
    
    // Calculate selected duration text
    private var durationText: String {
        let selectedDuration = (selectionEnd - selectionStart) * totalDuration
        return "\(formatTime(selectedDuration))/\(formatTime(totalDuration))"
    }
    
    var body: some View {
        VStack(spacing: 0) {
            // Drag Handle
            VStack(spacing: 0) {
                Rectangle()
                    .fill(Color.white.opacity(0.1))
                    .frame(width: 32, height: 4)
                    .clipShape(Capsule())
                    .padding(.top, 16)
            }
            .padding(.bottom, 12)
            
            // Header Section
            VStack(spacing: 12) {
                HStack(spacing: 4) {
                    Spacer()
                    
                    HStack(spacing: 4) {
                        Button(action: {
                            showTitleEditor = true
                        }) {
                            HStack(spacing: 4) {
                                Text(title)
                                    .font(Constants.Typography.mediumTitle)
                                    .foregroundColor(Constants.Colors.Foreground.primary)
                                    .tracking(0.32)
                                    .lineLimit(1)
                                
                                Image("Icon/edit")
                                    .resizable()
                                    .renderingMode(.template)
                                    .foregroundColor(Constants.Colors.Foreground.primary)
                                    .frame(width: 16, height: 16)
                            }
                        }
                        .buttonStyle(PlainButtonStyle())
                    }
                    
                    Spacer()
                }
                
                // Duration display
                Text(durationText)
                    .font(Constants.Typography.timecode)
                    .foregroundColor(Constants.Colors.Foreground.tertiary)
                    .tracking(0.24)
            }
            .padding(.horizontal, 24)
            .padding(.bottom, 24)
            
            // Audio Trimmer Section - Expandable container
            VStack {
                Spacer()
                
                HStack(alignment: .center, spacing: 16) {
                    // Play Button
                    Button(action: {
                        isPlaying.toggle()
                    }) {
                        ZStack {
                            RoundedRectangle(cornerRadius: 12)
                                .fill(Color.white.opacity(0.1))
                                .frame(width: 80, height: 80)
                            
                            Image(isPlaying ? "Icon/pause" : "Icon/play")
                                .resizable()
                                .renderingMode(.template)
                                .foregroundColor(Constants.Colors.Foreground.primary)
                                .frame(width: 24, height: 24)
                        }
                    }
                    .buttonStyle(PlainButtonStyle())
                    
                    // AudioTrimmer Component
                    AudioTrimmer(
                        selectionStart: $selectionStart,
                        selectionEnd: $selectionEnd,
                        isPlaying: $isPlaying,
                        totalDuration: totalDuration,
                        onSelectionChanged: { newStart, newEnd in
                            print("Selection changed: \(newStart) - \(newEnd)")
                        }
                    )
                    .frame(height: 80)
                }
                .padding(.horizontal, 24)
                
                Spacer()
            }
            
            // Bottom Section with Buttons and Upgrade Text
            VStack(spacing: 24) {
                // Button Section
                HStack(spacing: 12) {
                    LargeButton.secondary("Cancel") {
                        onCancel()
                        isPresented = false
                    }
                    
                    LargeButton(
                        title: "Continue",
                        variant: .primary,
                        action: {
                            let startTime = selectionStart * totalDuration
                            let endTime = selectionEnd * totalDuration
                            onContinue(startTime, endTime)
                            isPresented = false
                        }
                    )
                }
                .padding(.horizontal, 24)
                
                // Upgrade Text
                VStack(spacing: 0) {
                    HStack(spacing: 0) {
                        Text("1 min limit. ")
                            .font(Constants.Typography.xSmallRegular)
                            .foregroundColor(Constants.Colors.Foreground.inactive)
                        
                        Button(action: {
                            // Handle upgrade action
                            print("Upgrade tapped")
                        }) {
                            Text("Upgrade")
                                .font(Constants.Typography.xSmallRegular)
                                .foregroundColor(Constants.Colors.Foreground.inactive)
                                .underline()
                        }
                        .buttonStyle(PlainButtonStyle())
                        
                        Text(" to use longer audio (8 min)")
                            .font(Constants.Typography.xSmallRegular)
                            .foregroundColor(Constants.Colors.Foreground.inactive)
                    }
                    
                }
                .padding(.bottom, 8) // Account for safe area
            }
        }
        .background(Constants.Colors.Background.secondary)
        .alert("Edit Title", isPresented: $showTitleEditor) {
            TextField("Title", text: $title)
            Button("Save") {
                showTitleEditor = false
            }
            Button("Cancel", role: .cancel) {
                showTitleEditor = false
            }
        }
    }
}

// MARK: - Preview
#Preview {
    AudioTrimmerSelectionView(
        isPresented: .constant(true),
        totalDuration: 120.0, // 2 minutes
        currentPosition: 10.0  // 10 seconds
    ) {
        print("Cancel tapped")
    } onContinue: { startTime, endTime in
        print("Continue tapped - Selection: \(startTime)s to \(endTime)s")
    }
}
