//
//  LoginView.swift
//  AcaMate
//
//  Created by Sean Kim on 12/1/24.
//

import SwiftUI
import Combine

struct LoginView: View {
    @EnvironmentObject var appVM: AppViewModel
    @StateObject private var loginVM = LoginViewModel()
    @State var cancellables: Set<AnyCancellable> = []
    @Binding var naviState : NaviState
    
    @State var selectIdLogin: Bool = false
    
    @State var userId: String = ""
    @State var password: String = ""
    @State var isSecure: Bool = true
    @State var isSave: Bool = false
    
    
    var body: some View {
        VStack(spacing: 0) {
            Spacer().frame(height: 100)
            Image(.Logo.appIcon)
                .resizable()
                .frame(width: 200, height: 200)
//                .padding(.top, 80)
                .padding(.bottom, 84)
            
            /// 앱 아이콘 이미지
            VStack(spacing: 16) {
                Button {
                    // MARK: - TODO, 카카오 계정 로그인 구현
                    appVM.isLoading.toggle()
                    loginAction(type: .Kakao)
                } label: {
                    makeButton(image: Image(.Logo.kakaoIcon),color: Color(.Other.yellow), "카카오 계정으로 시작하기")
                }
                
                Button {
                    // MARK: - TODO, 애플 계정 로그인 구현
                    naviState.set(act: .MOVE, path: .Main)
                } label: {
                    makeButton(image: Image(.Logo.appleIcon), color: Color(.Text.black), "애플 계정으로 시작하기")
                }
            }
            .padding([.leading,.trailing], 28)
            
            Spacer(minLength: 1)

            
            /*
            VStack(spacing: 16) {
                
                Button {
                    // MARK: TO-DO
                    // 카카오 로그인 연동
                    naviState.set(act: .MOVE, path: .Main)
                } label: {
                    HStack(spacing: 24) {
                        Image("Kakao_Icon")
                            .resizable()
                            .frame(width: 32, height: 32)
                        Text("카카오 계정으로 시작하기")
                            .font(.nps(font: .regular, size: 16))
                            .foregroundStyle(Color(.Text.black))
                    }
                    .frame(maxWidth: .infinity)
                    .padding(12)
                    .background {
                        RoundedRectangle(cornerRadius: 12)
                            .foregroundStyle(Color(.Other.yellow))
                    }
                }
                .frame(maxWidth: .infinity)
                /// KAKAO 로그인 버튼
                
                Button {
                    // MARK: TO-DO
                    // 애플 로그인 연동
                } label: {
                    HStack(spacing: 24) {
                        Image(systemName: "apple.logo")
                            .resizable()
                            .accentColor(Color(.Text.white))
                            .frame(width: 32, height: 32)
                        
                        Text("애플 계정으로 시작하기")
                            .font(.nps(font: .regular, size: 16))
                            .foregroundStyle(Color(.Text.white))
                    }
                    .frame(maxWidth: .infinity)
                    .padding(12)
                    .background {
                        RoundedRectangle(cornerRadius: 12)
                            .foregroundStyle(Color(.Text.black))
                    }
                }
                .frame(maxWidth: .infinity)
                /// APPLE 로그인 버튼
            }
             */
            
        }
        .onAppear {
            subscribeLoginAction()
        }
        .frame(maxWidth: .infinity,maxHeight: .infinity)
        .fullDrawView(.Normal.normal)
    }
    func makeButton(image: Image, color: Color? = nil, _ body: String) -> some View {
        return HStack {
            image
                .resizable()
                .frame(width: 32, height: 32)
            Spacer(minLength: 12)
            Text("\(body)")
                .font(.nps(font: .regular, size: 16))
                .foregroundStyle(color == Color(.Text.black) ? Color(.Text.white) : Color(.Text.black))
            Spacer(minLength: 12)
        }
        .padding(12)
        .background {
            if let color = color {
                RoundedRectangle(cornerRadius: 12)
                    .foregroundStyle(color)
            }
        }
    }
    
    private func subscribeLoginAction() {
        loginVM.loginAction
            .sink { isTapped in
                if isTapped {
                    if userId.isEmpty || password.isEmpty {
                        appVM.alertData = SetAlertData().setErrorLogin()
                        appVM.showAlert.toggle()
                    }
                    else {
                        
                    }
                    printLog("로그인")
                }
            }
            .store(in: &cancellables)
    }
    
    private func loginAction(type: SNSLoginType) {
        LoginController().login(type)
            .flatMap{ snsId in
                loadAPIData(url: "\(API_URL)",
                            path: "/api/v1/in/user/login",
                            parameters: [
                                "sns_id": "\(snsId.snsId)",
                                "acctype": "\(type == .Apple ? "ST00": "ST01")"
                                        ],
                            decodingType: APIResponse<User_Academy>.self)
                
            }
            .sink { completion in
                switch completion {
                case .failure(let error):
                    printLog("\(error)")
                    appVM.isLoading.toggle()
                case .finished:
                    appVM.isLoading.toggle()
                }
            } receiveValue: { response in
                guard let ua = response as? APIResponse<User_Academy> else {return}
                if let bids = ua.data.toStringDict()["bid"] {
                    printLog(bids)
                    if let bidArray: [String] = jsonToSwift(bids) {
                        printLog(bidArray[0])
                    } else {
                        printLog("JSON 변환 실패")
                    }
                }
            }
            .store(in: &cancellables)
        
    }
}

//#Preview {
//    LoginView()
//}
