import APIClient
import ComponentLibrary
import Localization
import PaywallClient
import SwiftUI

struct PeriodPickerView: View {
    @Binding var selectedPeriod: Subscription.Period
    let data: BillingPeriodToggleResponse
    let onPeriodChanged: ((Subscription.Period) -> Void)?

    init(
        selectedPeriod: Binding<Subscription.Period>,
        data: BillingPeriodToggleResponse,
        onPeriodChanged: ((Subscription.Period) -> Void)? = nil
    ) {
        self._selectedPeriod = selectedPeriod
        self.data = data
        self.onPeriodChanged = onPeriodChanged
    }

    var body: some View {
        picker
            .overlay(alignment: .topTrailing) {
                if !data.discountBadge.text.isEmpty {
                    Text(data.discountBadge.text)
                        .typographyV1(.caption5)
                        .padding(1)
                        .padding(.horizontal, 4)
                        .background(Color(hex: data.discountBadge.backgroundColor))
                        .foregroundColor(Color(hex: data.discountBadge.textColor))
                        .clipShape(.capsule)
                        .offset(x: 24, y: -16)
                }
            }
            .onChange(of: selectedPeriod) { oldValue, newValue in
                if oldValue != newValue {
                    onPeriodChanged?(newValue)
                }
            }
    }
    
    @ViewBuilder
    var picker: some View {
        if #available(iOS 26.0, *) {
            Picker(L10n.FeaturePaywall.periodPicker, selection: $selectedPeriod) {
                Text(data.monthlyLabel.text)
                    .tag(Subscription.Period.month)
                Text(data.annualLabel.text)
                    .tag(Subscription.Period.year)
            }
            .pickerStyle(.segmented)
            .frame(width: 150, height: 40)
            .padding(2)
            .padding(.bottom, 1)
            .glassBackground(shape: .capsule, type: .clear, fallbackStyle: .clear, interactive: true)
        } else {
            Picker(L10n.FeaturePaywall.periodPicker, selection: $selectedPeriod) {
                Text(data.monthlyLabel.text)
                    .tag(Subscription.Period.month)
                Text(data.annualLabel.text)
                    .tag(Subscription.Period.year)
            }
            .pickerStyle(.segmented)
            .frame(width: 150, height: 40)
        }
    }
}

