//
//  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()
    
    var body: some View {
        BaseView(isLoading: $viewModel.isLoading) {
            if 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: "마이 페이지") {
                            Image("ic_settings")
                                .resizable()
                                .frame(width: 20, height: 20)
                                .onTapGesture {
                                    AppState.shared.setAppStep(step: .settings)
                                }
                        }
                        RefreshableScrollView(
                            refreshing: $viewModel.isLoading,
                            action: {
                                viewModel.getMypage()
                            }
                        ) {
                            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: 8) {
                                        Text("팔로잉 리스트")
                                            .frame(maxWidth: .infinity)
                                            .padding(.vertical, 13.3)
                                            .font(.custom(Font.bold.rawValue, size: 15.3))
                                            .foregroundColor(Color.grayee)
                                            .cornerRadius(6.7)
                                            .overlay(
                                                RoundedRectangle(cornerRadius: 6.7)
                                                    .stroke(Color.button, lineWidth: 1)
                                            )
                                            .contentShape(Rectangle())
                                            .onTapGesture {
                                                AppState.shared.setAppStep(step: .followingList)
                                            }
                                        
                                        Text("차단 리스트")
                                            .frame(maxWidth: .infinity)
                                            .padding(.vertical, 13.3)
                                            .font(.custom(Font.bold.rawValue, size: 15.3))
                                            .foregroundColor(Color.grayee)
                                            .cornerRadius(6.7)
                                            .overlay(
                                                RoundedRectangle(cornerRadius: 6.7)
                                                    .stroke(Color.button, lineWidth: 1)
                                            )
                                            .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)
                                    }
                                    
                                    if data.isAuth {
                                        CanChargeCouponButtonView()
                                            .frame(width: screenSize().width - 26.7)
                                            .padding(.top, 13.3)
                                            .onTapGesture {
                                                AppState.shared.setAppStep(step: .canCoupon)
                                            }
                                    }
                                    
                                    ReservationStatusView(data: data)
                                        .padding(.top, 33.3)
                                    
                                    if data.orderList.totalCount > 0 {
                                        OrderListView(items: data.orderList.items)
                                            .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)
                                            }
                                    }
                                }
                            }
                        }
                    }
                    .frame(width: geo.size.width, height: geo.size.height)
                }
                .onAppear {
                    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()
    }
}
