//
//  HeroView.swift
//  Gran Fondo
//
//  Created by Willem L. Middelkoop on 06/05/2024.
//

import SwiftUI
import StoreKit

struct HeroView: View {
    @Environment(\.presentationMode) var presentationMode
    
        // MARK: - Properties
    @EnvironmentObject private var entitlementManager: EntitlementManager
    @EnvironmentObject private var purchaseManager: PurchaseManager
    @EnvironmentObject var activityRecorder: ActivityRecorder
    
    @State private var selectedProduct: Product? = nil
    private let features: [String] = ["Unlimited runs and rides",
                                      "Fund new features & refinements",
                                      "Keep the app ad-free",
                                      "... help feed the family 🙂❤️🙏"]
    
    // MARK: - Layout
    var body: some View {
        if entitlementManager.hasPro {
            hasSubscriptionView
                .presentationDragIndicator(.visible)
                .background(.ultraThinMaterial)
                .presentationBackground(.clear)
        } else {
            subscriptionOptionsView
                .padding(.horizontal, 15)
                .padding(.vertical, 0)
                .onAppear {
                    Task {
                        await purchaseManager.loadProducts()
                    }
                }
                .interactiveDismissDisabled()
                .background(.ultraThinMaterial)
                .presentationBackground(.clear)
        }
    }
    
    // MARK: - Views
    private var hasSubscriptionView: some View {
        
        /*
        VStack(spacing: 20) {
            Image(systemName: "crown.fill")
                .foregroundStyle(.yellow)
                .font(Font.system(size: 100))
            
            Text("You've Unlocked Pro Access")
                .font(.system(size: 30.0, weight: .bold))
                .fontDesign(.rounded)
                .multilineTextAlignment(.center)
                .padding(.horizontal, 30)
        }
        .ignoresSafeArea(.all)*/
        VStack(alignment: .center, spacing: 20) {
            Spacer()
                
                Image("icon")
                    .resizable()
                    .aspectRatio(contentMode: .fill)
                    .frame(maxWidth: 85, maxHeight: 85)
                    .clipped()
                    .cornerRadius(8)
                
            
            Text("Thank You")
                .font(.system(size: 33.0, weight: .bold))
                .fontDesign(.rounded)
                .multilineTextAlignment(.center)
            
            Text("You are a hero!")
                .font(.system(size: 17.0, weight: .semibold))
                .fontDesign(.rounded)
                .multilineTextAlignment(.center)
                .padding(.horizontal, 20)
            
            Button(action: {
                presentationMode.wrappedValue.dismiss()
                
            }){
                Text("Let's Go!")
                    .foregroundColor(Color.white)
                    .padding()
                    .frame(maxWidth: .infinity)
                    .font(.system(size: 18))
                    .fontWeight(.semibold)
                    .fontDesign(.rounded)
            }.background(Color.black)
                .cornerRadius(8)
                .contentShape(Rectangle())
            Spacer()
        }.padding(30)
    }
    
    private var subscriptionOptionsView: some View {
        VStack(alignment: .center, spacing: 0) {
            if !purchaseManager.products.isEmpty {
                Spacer()
                proAccessView
                Spacer()
                featuresView
                VStack(spacing: 2.5) {
                    productsListView
                    purchaseSection
                }
            } else {
                ProgressView()
                    .progressViewStyle(.circular)
                    .scaleEffect(1.5)
                    .ignoresSafeArea(.all)
            }
        }
    }
    
    private var proAccessView: some View {
        VStack(alignment: .center, spacing: 0) {
            ZStack(alignment: .top){
                Image("icon")
                    .resizable()
                    .aspectRatio(contentMode: .fill)
                    .frame(width: 85, height: 85)
                    .clipped()
                    .cornerRadius(8)
                
                HStack(alignment: .top){
                    Spacer()
                    Button(action: {
                        presentationMode.wrappedValue.dismiss()
                    }){
                        Image(systemName: "xmark.circle.fill")
                            .resizable()
                            .aspectRatio(contentMode: .fill)
                            .frame(maxWidth: 30, maxHeight: 30)
                            .font(.system(size: 30, weight: .semibold))
                            .clipped()
                            .padding(.horizontal, 15)
                            .padding(.vertical, 20)
                            .foregroundColor(.primary.opacity(0.2))
                    }
                }
            }
            Text("Become a Hero")
                .font(.system(size: 33.0, weight: .bold))
                .fontDesign(.rounded)
                .multilineTextAlignment(.center)
            
            Text("Support Gran Fondo — Be a Hero!")
                .font(.system(size: 17.0, weight: .semibold))
                .fontDesign(.rounded)
                .multilineTextAlignment(.center)
                .padding(.horizontal, 20)
        }
    }
    
    private var featuresView: some View {
        VStack(spacing:0){
            Spacer(minLength: 0)
            List(features, id: \.self) { feature in
                HStack(alignment: .center) {
                    Image(systemName: "checkmark.circle")
                        .font(.system(size: 20, weight: .medium))
                        .foregroundStyle(.green)
                    
                    Text(feature)
                        .font(.system(size: 17.0, weight: .semibold, design: .rounded))
                        .multilineTextAlignment(.leading)
                }
                .padding(0)
                .listRowSeparator(.hidden)
                .listRowBackground(Color.clear)
                .listRowSpacing(0)
               
            }
            .frame(maxHeight: 180)
            .background(.clear)
            .scrollDisabled(true)
            .listStyle(.plain)
            .padding(.vertical, 0)
            Spacer(minLength: 5)
        }.padding(0)
        
    }
    
    private var productsListView: some View {
        List(purchaseManager.products, id: \.self) { product in
            SubscriptionItemView(product: product, selectedProduct: $selectedProduct)
        }
        .scrollDisabled(true)
        .listStyle(.plain)
        .listRowSpacing(2.5)
        .padding(0)
        .frame(height: CGFloat(purchaseManager.products.count) * 90, alignment: .bottom)
    }
    
    private var purchaseSection: some View {
        VStack(alignment: .center, spacing: 15) {
            purchaseButtonView
            
            HStack (alignment: .center,spacing:20){
                Button("Restore Purchases") {
                    Task {
                        await purchaseManager.restorePurchases()
                    }
                }
                .font(.system(size: 14.0, weight: .regular, design: .rounded))
                .frame(height: 15, alignment: .center)
                    
                Button("Privacy") {
                     let url = URL(string: "https://willem.com/etcetera/granfondo.app/privacy/")!
                     UIApplication.shared.open(url)
                 }
                .font(.system(size: 14.0, weight: .regular, design: .rounded))
                .frame(height: 15, alignment: .center)
                
                 Button("Terms of Use") {
                     let url = URL(string: "https://www.apple.com/legal/internet-services/itunes/dev/stdeula/")!
                     UIApplication.shared.open(url)
                 }
                 .font(.system(size: 14.0, weight: .regular, design: .rounded))
                 .frame(height: 15, alignment: .center)
            }
            Text("Subscriptions will automatically renew and you will be charged at the end of each period, unless you unsubscribe at least 24 hours before. To manage your subscription, access your Apple ID profile in your settings and look for the Subscriptions section.")
                .font(.system(size: 11.0, weight: .regular, design: .rounded))
                .lineLimit(nil)
                .foregroundColor(Color.primary)
                .fixedSize(horizontal: false, vertical: true)
                .multilineTextAlignment(.center)
                .opacity( ( self.selectedProduct == nil || self.selectedProduct?.subscription != nil ) ? 1.0 : 0.0)
                .padding(0)
        }
    }
    
    private var purchaseButtonView: some View {
        Button(action: {
            if let selectedProduct = selectedProduct {
                Task {
                    await purchaseManager.buyProduct(selectedProduct)
                }
            } else {
                print("Please select a product before purchasing.")
            }
        }) {
            RoundedRectangle(cornerRadius: 12.5)
                .overlay {
                    Text("Purchase")
                        .foregroundStyle(.white)
                        .font(.system(size: 16.5, weight: .semibold, design: .rounded))
                }
        }
        .padding(.horizontal, 20)
        .frame(height: 46)
        .disabled(selectedProduct == nil)
    }
}

// MARK: Subscription Item
struct SubscriptionItemView: View {
    var product: Product
    @Binding var selectedProduct: Product?
    
    var body: some View {
        ZStack {
            RoundedRectangle(cornerRadius: 12.5)
                .stroke(selectedProduct == product ? .blue : .secondary, lineWidth: 3.0)
                .background(RoundedRectangle(cornerRadius: 10).fill(Color.white))
            
            HStack {
                VStack(alignment: .leading, spacing: 8.5) {
                    Text(product.displayName)
                        .font(.system(size: 18.0, weight: .semibold, design: .rounded))
                        .multilineTextAlignment(.leading)
                        .foregroundColor(.black)
                        .fontDesign(.rounded)
                    
                    if let subscription = product.subscription {
                        if subscription.subscriptionPeriod.unit == Product.SubscriptionPeriod.Unit.month {
                            //Get full access for just
                            Text("For just \(product.displayPrice) / month")
                                .font(.system(size: 16.0, weight: .regular, design: .rounded))
                                .multilineTextAlignment(.leading)
                                .foregroundColor(.gray)
                        }else if product.subscription?.subscriptionPeriod.unit == Product.SubscriptionPeriod.Unit.year {
                            Text("For just \(product.displayPrice) / year")
                                .font(.system(size: 16.0, weight: .regular, design: .rounded))
                                .multilineTextAlignment(.leading)
                                .foregroundColor(.gray)
                        }
                    }else{
                        Text("One-time payment \(product.displayPrice)")
                            .font(.system(size: 16.0, weight: .regular, design: .rounded))
                            .multilineTextAlignment(.leading)
                            .foregroundColor(.gray)
                    }
                }
                Spacer()
                Image(systemName: selectedProduct == product ? "checkmark.circle.fill" : "circle")
                    .foregroundColor(selectedProduct == product ? .blue : .gray)
            }
            .padding(.horizontal, 20)
            .frame(height: 65, alignment: .center)
            
        }
        .onTapGesture {
            selectedProduct = product
        }
        .listRowSeparator(.hidden)
        .listRowBackground(Color.clear)
        
    }
}

    
    
    /*   var body: some View {
           VStack {
               Image("icon")
                   .resizable()
                   .scaledToFit()
                   .frame(width: 85, height: 85)
                   .padding(.top, 20)
               
               Text("By subscribing to Gran Fondo, you not only enhance your app experience but also support its commitment to privacy and ad-free usage. \n\nEvery subscription directly funds further development, helping me to test and integrate more Bluetooth sensors and refine features. (.. and feed the family 🙏❤️)\n\nThank you, Willem.")
                   .padding()
               
               Button("Hero (1 Month)") {
                   // Handle purchase
                   print("Buying Monthly Hero")
               }
               .padding()
               
               Button("Hero (1 Year)") {
                   // Handle purchase
                   print("Buying Yearly Hero")
               }
               .padding()
               
               Button("Hero (Lifetime)") {
                   // Handle purchase
                   print("Buying Lifetime Hero")
               }
               .padding()
               
               Button("Done") {
                   presentationMode.wrappedValue.dismiss()
               }
               .padding(.bottom, 20)
           }
       }
   }
*/
