import APIClient
import ComposableArchitecture
import Localization
import SwiftUI

struct ExtendModeWaveform: View {
    @Bindable var store: StoreOf<CustomCreatePlayer>
    let extendTimestamp: Double
    let clipDuration: Double
    let onExtendTimestampChanged: ((Double) -> Void)?
    
    var body: some View {
        VStack(spacing: 0) {
            ExtendWaveformTrimmer(
                selectionEnd: Binding(
                    get: { extendTimestamp / clipDuration },
                    set: { newValue in
                        let newTimestamp = newValue * clipDuration
                        onExtendTimestampChanged?(newTimestamp)
                    }
                ),
                totalDuration: clipDuration,
                elapsedTime: store.elapsedTime,
                isScrubbing: store.isScrubbing,
                extendTimestamp: extendTimestamp,
                waveformData: store.waveformData,
                onSelectionChanged: { newEnd in
                    let newTimestamp = newEnd * clipDuration
                    onExtendTimestampChanged?(newTimestamp)
                },
                onPlaybackScrubbing: { action in
                    store.send(.playbackScrubbing(action))
                },
                onPlaybackReachedExtendTimestamp: {
                    store.send(.pauseTapped)
                    store.send(.playbackScrubbing(.endScrubbing(0)))
                }
            )
            
            Text(L10n.FeatureCreateClip.extensionBeginsAfter(formatTimeForExtension(extendTimestamp)))
                .figmaMCPTypography(TypographyV1.FigmaMCP.xSmallRegular)
                .foregroundColor(Color.FigmaMCP.Semantic.fogDense)
                .tracking(0.24)
                .padding(.top, 12)
        }
        .onChange(of: store.elapsedTime) { oldValue, newValue in
            if !store.isScrubbing && newValue >= extendTimestamp && oldValue < extendTimestamp {
                store.send(.pauseTapped)
                store.send(.seekToStart)
            }
        }
    }
    
    private func formatTimeForExtension(_ seconds: Double) -> String {
        let minutes = Int(seconds) / 60
        let remainingSeconds = Int(seconds) % 60
        return String(format: "%d:%02ds", minutes, remainingSeconds)
    }
}

