//
//  LoginView.swift
//  WekoutThotViewer
//
//  Created by Trey Tartt on 6/18/24.
//

import SwiftUI

struct LoginView: View {
    @State var email: String = ""
    @State var password: String = ""
    @Environment(\.dismiss) var dismiss
    let completion: (() -> Void)
    @State var doingNetworkShit: Bool = false
    
    var body: some View {
        VStack {
            TextField("Email", text: $email)
                .textContentType(.username)
                .autocapitalization(.none)
                .frame(height: 55)
                .textFieldStyle(PlainTextFieldStyle())
                .padding([.horizontal], 4)
                .overlay(RoundedRectangle(cornerRadius: 16).stroke(Color(uiColor: .clear))).background(Color(uiColor: .init(red: 255/255, green: 255/255, blue: 255/255, alpha: 1)))
                .cornerRadius(8)
                .padding(.top, 25)
            
            
            SecureField("Password", text: $password)
                .textContentType(.password)
                .autocapitalization(.none)
                .frame(height: 55)
                .textFieldStyle(PlainTextFieldStyle())
                .padding([.horizontal], 4)
                .overlay(RoundedRectangle(cornerRadius: 16).stroke(Color(uiColor: .clear))).background(Color(uiColor: .init(red: 255/255, green: 255/255, blue: 255/255, alpha: 1)))
                .cornerRadius(8)
            
            if doingNetworkShit {
                ProgressView("Logging In")
                    .padding()
                    .foregroundColor(.white)
                    .progressViewStyle(CircularProgressViewStyle(tint: .white))
                    .scaleEffect(1.5, anchor: .center)
            } else {
                Button("Login", action: {
                    login()
                })
                .frame(maxWidth: .infinity, alignment: .center)
                .frame(height: 44)
                .foregroundColor(.blue)
                .background(.yellow)
                .cornerRadius(8)
                .padding()
                .frame(maxWidth: .infinity)
                .disabled(password.isEmpty || email.isEmpty)
            }
            
            Spacer()
        }
        .padding()
        .background(
            Image("icon")
                .resizable()
                .edgesIgnoringSafeArea(.all)
                .scaledToFill()
        )
    }
    
    func login() {
        let postData = [
            "email": email,
            "password": password
        ]
        doingNetworkShit = true
        UserStore.shared.login(postData: postData, completion: { success in
            doingNetworkShit = false
            if success {
                completion()
                dismiss()
            }
        })
    }
}

struct LoginView_Previews: PreviewProvider {
    static var previews: some View {
        LoginView(completion: {
            
        })
    }
}

