//
//  CanChargeView.swift
//  SodaLive
//
//  Created by klaus on 2023/08/11.
//

import SwiftUI
import StoreKit

enum CanChargeCurrentTab: String {
    case iap, pg
}

struct CanChargeView: View {
    
    @StateObject var storeManager = StoreManager()
    @StateObject var viewModel = CanChargeViewModel()
    
    @State var currentTab: CanChargeCurrentTab = .pg
    
    let refresh: () -> Void
    let afterCompletionToGoBack: Bool
    
    var body: some View {
        BaseView(isLoading: $storeManager.isLoading) {
            VStack(spacing: 13.3) {
                DetailNavigationBar(title: "충전하기")
                
                if UserDefaults.bool(forKey: .auth) {
                    CanChargeTabView(currentTab: $currentTab)
                }
                
                if UserDefaults.bool(forKey: .auth) && currentTab == .pg {
                    ScrollView(.vertical, showsIndicators: false) {
                        VStack(spacing: 13.3) {
                            ForEach(viewModel.cans, id: \.self) { item in
                                CanPgItemView(item: item)
                                    .onTapGesture {
                                        AppState.shared.setAppStep(
                                            step: .canPgPayment(canResponse: item, refresh: refresh, afterCompletionToGoBack: afterCompletionToGoBack)
                                        )
                                    }
                            }
                        }
                        .onAppear {
                            viewModel.getCans()
                        }
                    }
                } else {
                    ScrollView(.vertical, showsIndicators: false) {
                        VStack(spacing: 13.3) {
                            ForEach(storeManager.products, id: \.self) { item in
                                CanItemView(item: item)
                                    .onTapGesture {
                                        AppState.shared.setAppStep(
                                            step: .canPayment(canProduct: item, refresh: refresh, afterCompletionToGoBack: afterCompletionToGoBack)
                                        )
                                    }
                            }
                        }
                        .onAppear {
                            storeManager.getProducts()
                        }
                    }
                }
            }
        }
        .popup(isPresented: $storeManager.isShowPopup, type: .toast, position: .top, autohideIn: 1) {
            GeometryReader { geo in
                HStack {
                    Spacer()
                    Text(storeManager.errorMessage)
                        .padding(.vertical, 13.3)
                        .padding(.horizontal, 6.7)
                        .frame(width: geo.size.width - 66.7, alignment: .center)
                        .font(.custom(Font.medium.rawValue, size: 12))
                        .background(Color(hex: "9970ff"))
                        .foregroundColor(Color.white)
                        .multilineTextAlignment(.leading)
                        .fixedSize(horizontal: false, vertical: true)
                        .cornerRadius(20)
                        .padding(.top, 66.7)
                    Spacer()
                }
            }
        }
    }
}

struct CanItemView: View {
    
    let item: SKProduct
    
    var body: some View {
        HStack(spacing: 0) {
            Text(item.localizedTitle)
                .font(.custom(Font.bold.rawValue, size: 15.3))
                .foregroundColor(Color(hex: "eeeeee"))
            
            Spacer()
            
            Text("\(NumberFormatter.localizedString(from: item.price, number: .currency))")
                .font(.custom(Font.bold.rawValue, size: 15.3))
                .foregroundColor(Color(hex: "eeeeee"))
        }
        .padding(.horizontal, 13.3)
        .padding(.vertical, 23.3)
        .background(Color(hex: "111111"))
        .cornerRadius(16.7)
        .padding(.horizontal, 13.3)
        .frame(width: screenSize().width)
    }
}

struct CanPgItemView: View {
    let item: GetCanResponse
    
    var body: some View {
        HStack(spacing: 0) {
            Text(item.title)
                .font(.custom(Font.bold.rawValue, size: 15.3))
                .foregroundColor(Color(hex: "eeeeee"))
            
            Spacer()
            
            Text("\(item.price) 원")
                .font(.custom(Font.bold.rawValue, size: 15.3))
                .foregroundColor(Color(hex: "eeeeee"))
        }
        .padding(.horizontal, 13.3)
        .padding(.vertical, 23.3)
        .background(Color(hex: "111111"))
        .cornerRadius(16.7)
        .padding(.horizontal, 13.3)
        .frame(width: screenSize().width)
    }
}

struct CanChargeTabView: View {
    
    @Binding var currentTab: CanChargeCurrentTab
    
    var body: some View {
        VStack(spacing: 0) {
            HStack(spacing: 0) {
                let tabWidth = screenSize().width / 2
                
                CanChargeTab(
                    title: "PG",
                    action: {
                        if currentTab != .pg {
                            currentTab = .pg
                        }
                    },
                    color: {
                        currentTab == .pg ?
                        Color.grayee :
                        Color.gray77
                    },
                    width: tabWidth,
                    isShowDivider: { currentTab == .pg }
                )
                
                CanChargeTab(
                    title: "인 앱 결제",
                    action: {
                        if currentTab != .iap {
                            currentTab = .iap
                        }
                    },
                    color: {
                        currentTab == .iap ?
                        Color.grayee :
                        Color.gray77
                    },
                    width: tabWidth,
                    isShowDivider: { currentTab == .iap }
                )
            }
            
            Rectangle()
                .frame(width: screenSize().width, height: 1)
                .foregroundColor(Color.gray90.opacity(0.5))
        }
    }
}

struct CanChargeTab: View {
    let title: String
    let action: () -> Void
    let color: () -> Color
    let width: CGFloat
    let isShowDivider: () -> Bool
    
    var body: some View {
        Button(action: action) {
            VStack(spacing: 0) {
                Spacer()
                
                Text(title)
                    .font(.custom(Font.medium.rawValue, size: 16.7))
                    .foregroundColor(color())
                    .frame(width: width)
                
                Spacer()
                
                Rectangle()
                    .frame(width: width, height: 3)
                    .foregroundColor(Color.button.opacity(isShowDivider() ? 1 : 0))
            }
            .frame(height: 50)
        }
    }
}

struct CanChargeView_Previews: PreviewProvider {
    static var previews: some View {
        CanChargeView(refresh: {}, afterCompletionToGoBack: false)
    }
}
