import CoreHaptics
import SwiftUI

public struct WaveformSelectorControls: View {
    let showLeftHandleResetControl: Bool
    let showRightHandleResetControl: Bool
    let onLeftHandleReset: () -> Void
    let onRightHandleReset: () -> Void
    let bufferWidth: CGFloat
    let totalWidth: CGFloat
    let height: CGFloat
    let controlSize: CGFloat = 15.0

    public var body: some View {
        ZStack {
            if showRightHandleResetControl {
                resetButton(isLeft: false, action: onRightHandleReset)
            }
            if showLeftHandleResetControl {
                resetButton(isLeft: true, action: onLeftHandleReset)
            }
        }
        .frame(width: totalWidth, height: height)
    }

    public init(
        showLeftHandleResetControl: Bool,
        showRightHandleResetControl: Bool,
        onLeftHandleReset: @escaping () -> Void,
        onRightHandleReset: @escaping () -> Void,
        bufferWidth: CGFloat,
        totalWidth: CGFloat,
        height: CGFloat
    ) {
        self.showLeftHandleResetControl = showLeftHandleResetControl
        self.showRightHandleResetControl = showRightHandleResetControl
        self.onLeftHandleReset = onLeftHandleReset
        self.onRightHandleReset = onRightHandleReset
        self.bufferWidth = bufferWidth
        self.totalWidth = totalWidth
        self.height = height
    }

    private func resetButton(
        isLeft: Bool,
        action: @escaping () -> Void
    ) -> some View {
        Button {
            action()
            let generator = UIImpactFeedbackGenerator(style: .light)
            generator.impactOccurred()
        } label: {
            Circle()
                .fill(Color.SemanticV1.backgroundPrimary)
                .frame(width: controlSize, height: controlSize)
                .overlay(
                    Image.Icon.extend
                        .resizable()
                        .frame(width: 12, height: 12)
                        .offset(x: 0.75) // The icon on its own, when centered, is not visually-centered
                        .foregroundColor(Color.SemanticV1.iconPrimary)
                        .rotationEffect(isLeft ? .zero : .degrees(180))
                        .frame(width: 32, height: 32)
                        .contentShape(Circle())
                )
                .frame(width: 32, height: 32)
                .contentShape(Circle())
        }
        .frame(width: totalWidth, height: height, alignment: isLeft ? .trailing : .leading)
    }
}
