//
//  MyPageView.swift
//  SodaLive
//
//  Created by klaus on 2023/08/09.
//

import SwiftUI

import Bootpay
import BootpayUI
import PopupView
import RefreshableScrollView

struct MyPageView: View {
    
    @StateObject var viewModel = MyPageViewModel()
    
    @State private var payload = Payload()
    @AppStorage("token") private var token: String = UserDefaults.string(forKey: UserDefaultsKey.token)
    
    var body: some View {
        BaseView(isLoading: $viewModel.isLoading) {
            if !token.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty &&
                viewModel.isShowAuthView {
                BootpayUI(payload: payload, requestType: BootpayRequest.TYPE_AUTHENTICATION)
                    .onConfirm {
                        DEBUG_LOG("onConfirm: \($0)")
                        return true
                    }
                    .onCancel {
                        DEBUG_LOG("onCancel: \($0)")
                    }
                    .onError {
                        DEBUG_LOG("onError: \($0)")
                        viewModel.errorMessage = "본인인증 중 오류가 발생했습니다."
                        viewModel.isShowPopup = true
                        viewModel.isShowAuthView = false
                    }
                    .onDone {
                        DEBUG_LOG("onDone: \($0)")
                        viewModel.authVerify($0)
                    }
                    .onClose {
                        DEBUG_LOG("onClose")
                        viewModel.isShowAuthView = false
                    }
            } else {
                GeometryReader { geo in
                    VStack {
                        HomeNavigationBar(title: "마이 페이지") {
                            if !token.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
                                Image("ic_settings")
                                    .resizable()
                                    .frame(width: 20, height: 20)
                                    .onTapGesture {
                                        AppState.shared.setAppStep(step: .settings)
                                    }
                            }
                        }
                        if !token.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
                            ScrollView(.vertical, showsIndicators: false) {
                                VStack(spacing: 0) {
                                    if let data = viewModel.myPageResponse {
                                        MyInfoCardView(data: data) {
                                            viewModel.getMypage()
                                        }
                                        .frame(width: screenSize().width - 26.7)
                                        .padding(.top, 13.3)
                                        
                                        if UserDefaults.string(forKey: .role) == MemberRole.CREATOR.rawValue {
                                            Text("내 채널 보기")
                                                .frame(width: screenSize().width - 26.7, height: 46.7)
                                                .font(.custom(Font.bold.rawValue, size: 15.3))
                                                .foregroundColor(Color.grayee)
                                                .background(Color.button)
                                                .cornerRadius(6.7)
                                                .padding(.top, 26.7)
                                                .onTapGesture {
                                                    AppState.shared.setAppStep(step: .creatorDetail(userId: UserDefaults.int(forKey: .userId)))
                                                }
                                        }
                                        
                                        HStack(spacing: 10.7) {
                                            Text("팔로잉 리스트")
                                                .font(.custom(Font.bold.rawValue, size: 14.7))
                                                .foregroundColor(Color.button)
                                                .frame(maxWidth: .infinity)
                                                .padding(.vertical, 13.3)
                                                .background(Color.bg)
                                                .cornerRadius(6.7)
                                                .overlay(
                                                    RoundedRectangle(cornerRadius: 6.7)
                                                        .stroke(Color.button, lineWidth: 1.3)
                                                )
                                                .contentShape(Rectangle())
                                                .onTapGesture {
                                                    AppState.shared.setAppStep(step: .followingList)
                                                }
                                            
                                            Text("차단 리스트")
                                                .font(.custom(Font.bold.rawValue, size: 14.7))
                                                .foregroundColor(Color.button)
                                                .frame(maxWidth: .infinity)
                                                .padding(.vertical, 13.3)
                                                .background(Color.bg)
                                                .cornerRadius(6.7)
                                                .overlay(
                                                    RoundedRectangle(cornerRadius: 6.7)
                                                        .stroke(Color.button, lineWidth: 1.3)
                                                )
                                                .contentShape(Rectangle())
                                                .onTapGesture {
                                                    AppState.shared.setAppStep(step: .blockList)
                                                }
                                        }
                                        .padding(.top, 26.7)
                                        .padding(.horizontal, 13.3)
                                        
                                        if UserDefaults.int(forKey: .userId) != 17958 {
                                            CanCardView(data: data) {
                                                viewModel.getMypage()
                                            }
                                            .frame(width: screenSize().width - 26.7)
                                            .padding(.top, 26.7)
                                            
                                            HStack(spacing: 6.7) {
                                                Text("\(data.point)")
                                                    .font(.custom(Font.bold.rawValue, size: 18.3))
                                                    .foregroundColor(.grayee)
                                                
                                                Image("ic_point")
                                                    .resizable()
                                                    .frame(width: 20, height: 20)
                                                
                                                Spacer()
                                            }
                                            .padding(.horizontal, 13.3)
                                            .padding(.vertical, 16.7)
                                            .frame(width: screenSize().width - 26.7)
                                            .background(Color.gray22)
                                            .cornerRadius(6.7)
                                            .padding(.top, 13.3)
                                        }
                                        
                                        if data.isAuth {
                                            CanChargeCouponButtonView()
                                                .frame(width: screenSize().width - 26.7)
                                                .padding(.top, 13.3)
                                                .onTapGesture {
                                                    AppState.shared.setAppStep(step: .canCoupon)
                                                }
                                        }
                                        
                                        VStack(alignment: .leading, spacing: 13.3) {
                                            Text("내 보관함")
                                                .font(.custom(Font.bold.rawValue, size: 18.3))
                                                .foregroundColor(Color.grayee)
                                            
                                            HStack(spacing: 10.7) {
                                                Text("구매목록")
                                                    .font(.custom(Font.bold.rawValue, size: 14.7))
                                                    .foregroundColor(Color.button)
                                                    .frame(maxWidth: .infinity)
                                                    .padding(.vertical, 13.3)
                                                    .background(Color.bg)
                                                    .cornerRadius(6.7)
                                                    .overlay(
                                                        RoundedRectangle(cornerRadius: 6.7)
                                                            .stroke(Color.button, lineWidth: 1.3)
                                                    )
                                                    .contentShape(Rectangle())
                                                    .onTapGesture {
                                                        AppState.shared.setAppStep(step: .myBox(currentTab: .orderlist))
                                                    }
                                                
                                                Text("재생목록")
                                                    .font(.custom(Font.bold.rawValue, size: 14.7))
                                                    .foregroundColor(Color.button)
                                                    .frame(maxWidth: .infinity)
                                                    .padding(.vertical, 13.3)
                                                    .background(Color.bg)
                                                    .cornerRadius(6.7)
                                                    .overlay(
                                                        RoundedRectangle(cornerRadius: 6.7)
                                                            .stroke(Color.button, lineWidth: 1.3)
                                                    )
                                                    .contentShape(Rectangle())
                                                    .onTapGesture {
                                                        AppState.shared.setAppStep(step: .myBox(currentTab: .playlist))
                                                    }
                                            }
                                        }
                                        .padding(.top, 33)
                                        .padding(.horizontal, 13.3)
                                        
                                        ReservationStatusView(data: data)
                                            .padding(.top, 40)
                                        
                                        ServiceCenterButtonView()
                                            .padding(.top, 40)
                                        
                                        if !data.isAuth {
                                            AuthButtonView()
                                                .padding(.top, 40)
                                                .onTapGesture {
                                                    viewModel.isShowAuthView = true
                                                }
                                        }
                                        
                                        if let url = URL(string: "https://blog.naver.com/sodalive_official"),
                                           UIApplication.shared.canOpenURL(url) {
                                            Image("img_how_to_use")
                                                .resizable()
                                                .frame(
                                                    width: screenSize().width,
                                                    height: (200 * screenSize().width) / 1080
                                                )
                                                .padding(.vertical, 40)
                                                .onTapGesture {
                                                    UIApplication.shared.open(url)
                                                }
                                        }
                                    }
                                }
                            }
                        } else {
                            ScrollView(.vertical, showsIndicators: false) {
                                VStack(spacing: 24) {
                                    HStack(spacing: 6.7) {
                                        Image("ic_logo_circle_gray")
                                        
                                        Text("Login")
                                            .font(.custom(Font.medium.rawValue, size: 32))
                                            .foregroundColor(.gray90)
                                    }
                                    .padding(20)
                                    .frame(maxWidth: .infinity)
                                    .background(Color.bg)
                                    .cornerRadius(6.7)
                                    .contentShape(Rectangle())
                                    .padding(.horizontal, 13.3)
                                    .padding(.top, 24)
                                    .onTapGesture {
                                        AppState.shared
                                            .setAppStep(step: .login)
                                    }
                                    
                                    HStack(spacing: 0) {
                                        HStack(spacing: 6.7) {
                                            Text("0")
                                                .font(.custom(Font.bold.rawValue, size: 18.3))
                                                .foregroundColor(.grayee)
                                            
                                            Image("ic_can")
                                                .resizable()
                                                .frame(width: 20, height: 20)
                                            
                                            Image("ic_forward")
                                                .resizable()
                                                .frame(width: 20, height: 20)
                                        }
                                        .onTapGesture {
                                            AppState.shared
                                                .setAppStep(step: .login)
                                        }
                                        
                                        Spacer()
                                        
                                        HStack(spacing: 7) {
                                            Image("ic_coin_w")
                                                .resizable()
                                                .frame(width: 26.7, height: 26.7)
                                            
                                            Text("충전")
                                                .font(.custom(Font.bold.rawValue, size: 12))
                                                .foregroundColor(Color(hex: "b38fff"))
                                        }
                                        .padding(.horizontal, 11.3)
                                        .padding(.vertical, 7)
                                        .overlay(
                                            RoundedRectangle(cornerRadius: CGFloat(16.7))
                                                .stroke(lineWidth: 1)
                                                .foregroundColor(Color(hex: "b38fff"))
                                        )
                                        .cornerRadius(16.7)
                                        .onTapGesture {
                                            AppState.shared
                                                .setAppStep(step: .login)
                                        }
                                    }
                                    .frame(maxWidth: .infinity)
                                    .padding(.horizontal, 13.3)
                                    .padding(.vertical, 10)
                                    .background(Color.gray22)
                                    .cornerRadius(6.7)
                                    .padding(.horizontal, 13.3)
                                    
                                    ServiceCenterButtonView()
                                        .padding(.horizontal, 13.3)
                                    
                                    if let url = URL(string: "https://blog.naver.com/sodalive_official"),
                                       UIApplication.shared.canOpenURL(url) {
                                        Image("img_how_to_use")
                                            .resizable()
                                            .frame(
                                                width: screenSize().width,
                                                height: (200 * screenSize().width) / 1080
                                            )
                                            .onTapGesture {
                                                UIApplication.shared.open(url)
                                            }
                                    }
                                }
                            }
                        }
                    }
                    .frame(width: geo.size.width, height: geo.size.height)
                }
                .onAppear {
                    if !token.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
                        viewModel.getMypage()
                    }
                }
            }
        }
        .popup(isPresented: $viewModel.isShowPopup, type: .toast, position: .top, autohideIn: 2) {
            GeometryReader { geo in
                HStack {
                    Spacer()
                    Text(viewModel.errorMessage)
                        .padding(.vertical, 13.3)
                        .frame(width: geo.size.width - 66.7, alignment: .center)
                        .font(.custom(Font.medium.rawValue, size: 12))
                        .background(Color.button)
                        .foregroundColor(Color.white)
                        .multilineTextAlignment(.center)
                        .cornerRadius(20)
                        .padding(.top, 66.7)
                    Spacer()
                }
            }
        }
        .onAppear {
            payload.applicationId = BOOTPAY_APP_ID
            payload.price = 0
            payload.pg = "다날"
            payload.method = "본인인증"
            payload.orderName = "본인인증"
            payload.authenticationId = "\(UserDefaults.string(forKey: .nickname))__\(String(NSTimeIntervalSince1970))"
        }
    }
}

struct MyPageView_Previews: PreviewProvider {
    static var previews: some View {
        MyPageView()
    }
}