//
//  PurchaseListView.swift
//  PadelClub
//
//  Created by Laurent Morvillier on 22/04/2024.
//

import SwiftUI
import StoreKit
import LeStorage

class PurchaseManager: ObservableObject {
    
    static let main: PurchaseManager = PurchaseManager()
    
    fileprivate var _products: [Product] = []
//    fileprivate var _purchases: [Purchase] = []
    
    @Published var purchaseRows: [PurchaseRow] = []
    
    init() {

        NotificationCenter.default.addObserver(self, selector: #selector(_purchasesChanged(notification:)), name: NSNotification.Name.StoreEventHappened, object: nil)
        
        let identifiers: [String] = StoreItem.allCases.map { $0.rawValue }
        Task {
            do {
                self._products = try await Product.products(for: identifiers)
                self._buildRowsOnMainThread()
            } catch {
                Logger.error(error)
            }
        }
    }

    @objc fileprivate func _purchasesChanged(notification: Notification) {
        self._buildRowsOnMainThread()
    }
    
    fileprivate func _buildRowsOnMainThread() {
        
        DispatchQueue.main.async {
            self._buildRows()
        }
        
    }
    
    fileprivate func _buildRows() {
        
        var rows: [PurchaseRow] = []
        let userPurchases: [StoreKit.Transaction] = Guard.main.userFilteredPurchases()
        
        let subscriptions: [StoreItem] = StoreItem.allCases.filter { !$0.isConsumable }
        for subscription in subscriptions {
            
            if let userPurchase = userPurchases.first(where: { $0.productID == subscription.rawValue }), let product = self._products.first(where: { $0.id == subscription.rawValue }) {
                
                rows.append(PurchaseRow(id: userPurchase.originalID, name: product.displayName, item: subscription))
            }
        }
        
        // Units
        let remainingTournaments = Guard.main.remainingTournaments
        if remainingTournaments > 0 {
            let unitItem: StoreItem = StoreItem.unit
            if let product = self._products.first(where: { $0.id == unitItem.rawValue } ) {
                rows.append(PurchaseRow(id: 0, name: product.displayName, item: unitItem, quantity: remainingTournaments))
            }
        }
        
        Logger.log("purchases = \(rows)")
        
        self.purchaseRows = rows
    }
    
}

struct PurchaseListView: View {
    
    @ObservedObject var manager = PurchaseManager()
    
    var body: some View {
        
        if self.manager.purchaseRows.count > 0 {
            
            Section {
                ForEach(self.manager.purchaseRows) { purchaseRow in
                    
                    Link(destination: URLs.subscriptions.url) {
                        PurchaseView(purchaseRow: purchaseRow)
                    }
                }
            } header: {
                Text("Vos achats")
            }
            
        }
    }
}

struct PurchaseView: View {
    
    var purchaseRow: PurchaseRow
    
    var body: some View {
        HStack {
            Image(systemName: self.purchaseRow.item.systemImage)
                .foregroundColor(.accentColor).font(.title2)
            Text(self.purchaseRow.name)
            Spacer()
            if let _ = purchaseRow.quantity {
                let remaining = Guard.main.remainingTournaments
                Text("\(remaining)")
            }
        }
    }
}

//#Preview {
//    PurchaseListView()
//}
