//
//  AccountView.swift
//  Werkout_ios
//
//  Created by Trey Tartt on 6/15/23.
//

import Foundation
import SwiftUI

struct AccountView: View {
    @State var completedWorkouts: [CompletedWorkout]?
    @ObservedObject var userStore = UserStore.shared
    @State var showCompletedWorkouts: Bool = false
    @AppStorage(Constants.phoneThotStyle) private var phoneThotStyle: ThotStyle = .never
    @AppStorage(Constants.extThotStyle) private var extThotStyle: ThotStyle = .never
    @AppStorage(Constants.extShowNextVideo) private var extShowNextVideo: Bool = false
    @AppStorage(Constants.thotGenderOption) private var thotGenderOption: String = "female"
    
    var body: some View {
        VStack(alignment: .leading) {
            if let registeredUser = userStore.registeredUser {
                if let nickName = registeredUser.nickName {
                    Text(nickName)
                        .font(.title)
                }
                
                HStack {
                    Text(registeredUser.firstName ?? "-")
                    Text(registeredUser.lastName ?? "-")
                }
                
                if let email = registeredUser.email {
                    Text(email)
                }
            }
            
            if let completedWorkouts = completedWorkouts {
                VStack(alignment: .leading) {
                    Divider()
                    Text("Workout History:")
                    HStack {
                        Text("Number of workouts:")
                        Text("\(completedWorkouts.count)")
                    }
                    
                    if let lastWorkout = completedWorkouts.last {
                        HStack {
                            Text("Last workout:")
                            Text(lastWorkout.workoutStartTime)
                        }
                        
                        Button("View All Workouts", action: {
                            showCompletedWorkouts = true
                        })
                        .frame(maxWidth: .infinity, alignment: .center)
                        .frame(height: 44)
                        .foregroundColor(.blue)
                        .background(.yellow)
                        .cornerRadius(8)
                        .padding()
                        .frame(maxWidth: .infinity)
                    }
                    
                }
            }
            Divider()
            
            if userStore.registeredUser?.NSFWValue ?? false {
                Group {
                    Text("Phone THOT Style:")
                    Picker("Phone THOT Style:", selection: $phoneThotStyle) {
                        ForEach(ThotStyle.allCases, id: \.self) { style in
                            Text(style.stringValue())
                                .tag(phoneThotStyle.rawValue)
                        }
                    }
                    .pickerStyle(.segmented)
                    
                    Divider()
                    
                    Text("External THOT Style:")
                    Picker("External THOT Style:", selection: $extThotStyle) {
                        ForEach(ThotStyle.allCases, id: \.self) { style in
                            Text(style.stringValue())
                                .tag(extThotStyle.rawValue)
                        }
                    }
                    .pickerStyle(.segmented)
                    
                    if let genderOptions = DataStore.shared.nsfwGenderOptions {
                        Divider()
                        Text("Video Gender:")
                        Picker("Video Gender:", selection: $thotGenderOption) {
                            ForEach(genderOptions, id: \.self) { option in
                                Text(option.capitalized)
                                    .tag(option.lowercased())
                            }
                        }
                        .pickerStyle(.segmented)
                    }
                }
            }
            
            Group {
                Divider()
                
                Toggle(isOn: $extShowNextVideo, label: {
                    Text("Show next up video")
                })
            }
            
            Spacer()
            
            HStack {
                Button("Logout", action: {
                    userStore.logout()
                })
                .frame(maxWidth: .infinity, alignment: .center)
                .frame(height: 44)
                .foregroundColor(.white)
                .background(.red)
                .cornerRadius(8)
                .padding()
                .frame(maxWidth: .infinity)
                
                Button(action: {
                    userStore.refreshUserData()
                }, label: {
                    Image(systemName: "arrow.triangle.2.circlepath")
                })
                .frame(width: 44, height: 44)
                .foregroundColor(.white)
                .background(.green)
                .cornerRadius(8)
                .padding()
                .frame(maxWidth: .infinity)
            }
        }
        .padding()
        .sheet(isPresented: $showCompletedWorkouts) {
            if let history = completedWorkouts {
                WorkoutHistoryView(completedWorkouts: history)
            }
        }
        .onAppear{
            if completedWorkouts == nil {
                fetchCompletedWorkouts()
            }
        }
        
    }
    
    func fetchCompletedWorkouts() {
        CompletedWorkoutFetchable().fetch(completion: { result in
            switch result {
            case .success(let model):
                completedWorkouts = model
            case .failure(let failure):
                fatalError(failure.localizedDescription)
            }
        })
    }
}

struct AccountView_Previews: PreviewProvider {
    static let userStore = UserStore.shared
    static let completedWorkouts = PreviewData.parseCompletedWorkouts()
    
    static var previews: some View {
        AccountView(completedWorkouts: completedWorkouts)
            .onAppear{
                userStore.setFakeUser()
            }
    }
}
