//
//  InputUserNameView.swift
//  forShip
//
//  Created by Mamoru Sugita on 2023/10/13.
//

import SwiftUI

struct InputUserNameView: View {
    @ObservedObject var sessionLogin: SessionLogin = SessionLogin()
    @Binding var isLogin: Bool
    @Binding var param: LoginViewParam
    @Binding var viewMode : LoginViewMode
    @State private var isAlert = false
    @State private var alertType: AlertType = .userNameEmpty
    let itemHPadding: Double = 16
    let dialogBottomPadding: Double = 32
    let textFieldHeight: Double = 40
    let inputAreaHeight: Double = 150
    let dialogHeight: CGFloat = 250
    let dialogWidth = UIScreen.main.bounds.width - 32

    enum AlertType {
        case userNameEmpty
        case loginFailure
    }

    var body: some View {
        HStack {
            Spacer()
                .frame(width: itemHPadding)
            VStack{
                Spacer()

                VStack(alignment: .leading) {
                    Text("JRC Ship")
                        .padding(.leading, 4)
                        .bold()
                        .foregroundColor(.white)

                    HStack{
                        Image("account")
                            .padding(.horizontal, 4)
                            .foregroundColor(.white)
                        TextField(
                            "",
                            text: $param.userName,
                            prompt: Text("Please set user name")
                                .foregroundColor(.white)
                        )
                        .frame(height: textFieldHeight)
                        .padding(.trailing)
                        .foregroundColor(.white)
                    }

                    Divider()
                        .frame(height: 2)
                        .background(Color(.white))
                }
                .frame(height: inputAreaHeight)



                Spacer()

                Button(action: {
                    if param.userName.isEmpty {
                        isAlert = true
                        alertType = .userNameEmpty
                    } else {
                        //TODO: API通信 ログイン認証処理
                        print(debug: "signin: id(\(param.shipId)), pass(\(param.password)), name(\(param.userName))")
                        isAlert = false
//                        param.shipId = "jrcetest01@gmail.com"
//                        param.password = "JRCEtest01_"
                        let login = ReqLogin(Id: param.shipId, Password: param.password)
                        sessionLogin.RequestLogin(login, completion: responseLogin)
                    }
                }, label: {
                    Text("Sign In")
                        .frame(height: 50)
                        .frame(maxWidth: .infinity)
                        .foregroundColor(ColorSet.ButtonText.color)
                        .background(ColorSet.PrimaryActiveIcon.color)
                })
                .alert(isPresented: $isAlert) {
                    switch alertType {
                    case .userNameEmpty:
                        return Alert(title: Text("error"),
                                     message: Text("User Nmae not entered.")
                        )

                    case .loginFailure:
                        return Alert(title: Text("error"),
                                     message: Text("Login failure."),
                                     dismissButton: .default(Text("OK"), action: {viewMode = .SelectType})
                        )
                    }
                }
                Spacer()
                    .frame(height: dialogBottomPadding)
            }

            Spacer()
                .frame(width: itemHPadding)
        }
        .frame(width: dialogWidth, height: dialogHeight)
        .background(ColorSet.BackgroundSecondary.color)
    }

    func responseLogin(result: Result<Data, APIError>) {
        print(debug: "calld")
        switch result {
        case .success(let resultData):
            let jsonstr = String(data: resultData, encoding: .utf8)!
            Preferences.ShipId = param.shipId
            Preferences.ShipPassword = param.password
            Preferences.lastLoginDate_Int64 = DateTextLib.Date2UnixTime(date: Date())
            isLogin = true
            isAlert = false
        case .failure(let errorCode):
            param.shipId = ""
            param.password = ""
            isLogin = false
            isAlert = true
            alertType = .loginFailure
            break
        }
    }
}

#Preview {
    InputUserNameView(isLogin: .constant(false), param: .constant(LoginViewParam()), viewMode: .constant(.InputIdPassword))
}
