import APIClient
import ComponentLibrary
import Localization
import PaywallClient
import SwiftUI

struct SubscriptionCardViewV2: View {
    let subscription: Subscription?
    let isSubscribed: Bool
    let plan: PlanMarketingResponse
    let isSelected: Bool
    let upsellAvailable: Bool
    let isDisabled: Bool
    let currencyCode: String?
    let action: () -> Void
    
    private let priceFormatter: NumberFormatter

    init(
        subscription: Subscription?,
        isSubscribed: Bool,
        plan: PlanMarketingResponse,
        isSelected: Bool,
        upsellAvailable: Bool,
        isDisabled: Bool = false,
        currencyCode: String?,
        action: @escaping () -> Void
    ) {
        self.subscription = subscription
        self.isSubscribed = isSubscribed
        self.plan = plan
        self.isSelected = isSelected
        self.upsellAvailable = upsellAvailable
        self.isDisabled = isDisabled
        self.currencyCode = currencyCode
        self.action = action
        
        let formatter = NumberFormatter()
        formatter.numberStyle = .currency
        formatter.currencyCode = currencyCode ?? subscription?.currencyCode ?? "USD"
        self.priceFormatter = formatter
    }

    private func formatPrice(_ price: Double) -> String {
        if let formatted = priceFormatter.string(from: NSNumber(value: price)) {
            if priceFormatter.currencyCode == "USD" {
                return formatted.replacingOccurrences(of: ".00", with: "")
            }
            return formatted
        }
        return String(format: "%.2f", price)
    }

    var priceString: String {
        guard let subscription else { return "" }
        // When discount is available, show discount price as main price
        if let discountPrice = subscription.discountPrice, upsellAvailable {
            return formatPrice(discountPrice)
        }
        return formatPrice(subscription.price)
    }

    var regularPriceString: String? {
        guard let subscription, upsellAvailable,
              subscription.discountPrice != nil else {
            return nil
        }
        // Show regular price as strikethrough when discount is available
        return formatPrice(subscription.price)
    }

    var annualPriceString: String? {
        guard let subscription else { return nil }
        if subscription.period == .year {
            if let discountYearPrice = subscription.discountYearPrice, upsellAvailable {
                return formatPrice(discountYearPrice)
            } else if let yearPrice = subscription.yearPrice {
                return formatPrice(yearPrice)
            }
        }
        return nil
    }

    var stickerUrl: String? {
        if let period = subscription?.period, let sticker = plan.stickers {
            if period == .year {
                return sticker.annual
            } else {
                return sticker.monthly
            }
        }
        return nil
    }

    var body: some View {
        Button(action: action) {
            content
        }
        .buttonStyle(ScaleButtonStyle(scaleAmount: 0.98))
        .disabled(isDisabled)
        .opacity(isDisabled ? 0.5 : 1.0)
    }

    var content: some View {
        HStack(spacing: 12) {
            toggle
            mainContent
        }
        .frame(maxWidth: .infinity, alignment: .leading)
        .padding(.vertical, 20)
        .padding(.horizontal, 16)
        .glassBackground(shape: .rect(cornerRadius: 16.0), type: .regular, fallbackStyle: .ultraThinMaterial, interactive: false)
        .overlay { borderOverlay }
        .overlay(alignment: .topLeading) { currentPlanBadge }
        .zIndex(1)
        .overlay(alignment: .bottomTrailing) { stickerOverlay }
        .animation(.snappy(duration: 0.15), value: isSelected)
    }

    private var mainContent: some View {
        HStack(alignment: .top, spacing: 4) {
            planInfoSection
            if subscription != nil, !isSubscribed {
                pricingSection
            }
        }
    }

    private var planInfoSection: some View {
        VStack(alignment: .leading, spacing: 4) {
            Text(plan.displayName.text)
                .typographyV1(.subscriptionCardTitle)

            Text(plan.tagline.text)
                .typographyV1(.subscriptionCardSubtitle)
                .foregroundStyle(Color.SemanticV1.textTertiary)
                .lineLimit(2)
        }
    }

    private var pricingSection: some View {
        VStack(alignment: .trailing, spacing: 4) {
            priceDisplay
            if let annualPriceString {
                annualPriceDisplay(annualPriceString)
            }
        }
        .frame(maxWidth: .infinity, alignment: .trailing)
    }

    private var priceDisplay: some View {
        HStack(alignment: .firstTextBaseline, spacing: 4) {
            if let regularPriceString, !regularPriceString.isEmpty {
                Text(regularPriceString)
                    .typographyV1(.heading4)
                    .foregroundStyle(Color.SemanticV1.textTertiary)
                    .strikethrough()
                    .lineLimit(1)

                Text(priceString)
                    .typographyV1(.subscriptionCardTitle)
                    .foregroundStyle(Color.SemanticV2.accentPink)
            } else {
                Text(priceString)
                    .typographyV1(.subscriptionCardTitle)
                    .foregroundStyle(Color.SemanticV1.textPrimary)
            }

            Text("/\(Subscription.Period.month.title)")
                .typographyV1(.body1)
                .foregroundStyle(.secondary)
        }
        .lineLimit(1)
        .minimumScaleFactor(0.5)
    }

    private func annualPriceDisplay(_ price: String) -> some View {
        Text(L10n.FeaturePaywall.billedAnnually(price))
            .typographyV1(.subscriptionCardSubtitle)
            .foregroundStyle(Color.SemanticV1.textTertiary)
            .opacity(0.5)
    }

    private var borderOverlay: some View {
        RoundedRectangle(cornerRadius: 16)
            .stroke(Color.SemanticV2.accentPink, lineWidth: isSelected ? 2 : 0)
    }

    @ViewBuilder
    private var currentPlanBadge: some View {
        if isSubscribed {
            Text(L10n.FeaturePaywall.currentPlan)
                .typographyV1(.subtitleSmall)
                .frame(height: 22)
                .padding(.horizontal, 10)
                .background {
                    if isSelected {
                        Capsule()
                            .fill(Color.SemanticV2.accentPink)
                    } else {
                        Capsule()
                            .fill(Color.SemanticV2.backgroundTertiary)
                    }
                }
                .padding(.leading, 16)
                .offset(y: -12)
        }
    }

    @ViewBuilder
    private var stickerOverlay: some View {
        if let stickerUrl, upsellAvailable, !isSubscribed {
            RemoteImage(url: stickerUrl, fallbackId: nil, backgroundColor: .clear)
                .frame(width: 56, height: 42)
                .offset(x: -14, y: 14)
                .zIndex(2)
        }
    }

    var toggle: some View {
        Circle()
            .strokeBorder(Color.SemanticV1.textPrimary.opacity(0.3), lineWidth: 1.0)
            .background(Color.SemanticV1.textPrimary.opacity(0.1), in: .circle)
            .frame(width: 22, height: 22)
            .overlay {
                if isSelected {
                    Image.Icon.checkV1
                        .renderingMode(.template)
                        .resizable()
                        .aspectRatio(contentMode: .fit)
                        .padding(4)
                        .foregroundStyle(Color.SemanticV2.accentPink)
            }
        }
    }
}
