//
//  ResevationView.swift
//  ios
//
//  Created by Tom Burke on 8/5/21.
//  Copyright © 2021 Bruin Fitness. All rights reserved.
//

import SwiftUI

struct ReservationView: View {
    @State private var isReserved = false
    @State private var isShowingWorkoutDetailSheet = false
    @EnvironmentObject var workoutClassVM: WorkoutClassViewModel
    @EnvironmentObject var authVM: AuthViewModel
    var docId: String
    var classDate: Date
    
    var body: some View {
        VStack {
            VStack(alignment: .leading){
            Divider()
            
            HStack{
                Label(
                    title: {
                        Text("\(workoutClassVM.workoutClass.classTimestamp.dayOfWeek), \(workoutClassVM.workoutClass.classTimestamp.abbreviatedMonth) \(workoutClassVM.workoutClass.classTimestamp.dayOfMonth) • \(workoutClassVM.workoutClass.time)")
                    },
                    icon: { Image(systemName: "calendar") }
                )
                Spacer()
            }
            Divider()
            if workoutClassVM.workoutClass.workoutType != "Open Gym"{
                HStack{
                    Button(action: {
                        self.isShowingWorkoutDetailSheet.toggle()
                            }) {
                                Text("View Workout")
                            }
                    .sheet(isPresented: self.$isShowingWorkoutDetailSheet) {
                                VStack {
                                    WorkoutDetailView(workoutType: workoutClassVM.workoutClass.workoutType)
                                    Button("Dismiss",
                                           action: { self.isShowingWorkoutDetailSheet.toggle() })
                                        .foregroundColor(Color("bruinGreenColor"))
                                        .padding()
                                }
                            }
                    Spacer()
                }
                Divider()
            }
            
                Text("\(String(workoutClassVM.workoutClass.reservationCnt)) Attendees (\(workoutClassVM.workoutClass.maxReservationCnt) max)").bold()
                ScrollView {
                    ForEach(workoutClassVM.workoutClass.reservedUsers ?? [], id: \.uid) { reservedUser in
                        HStack {
                            AttendeeRowView(url: reservedUser.photoURL, memberName: reservedUser.displayName ?? "")
                            Spacer()
                        }.padding(.init(top: 3, leading: 3, bottom: 0, trailing: 0))
                    }
                }
            Spacer()
            }
    
            // Reservation button state
            if workoutClassVM.workoutClass.classTimestamp < Date() {
                Text("Reservations Closed")
                    .frame(minWidth: 0, maxWidth: .infinity)
                    .font(.system(.title, design: .rounded))
                    .padding()
                    .foregroundColor(.gray)
                    .overlay(
                        RoundedRectangle(cornerRadius: 25)
                            .stroke(Color.gray, lineWidth: 2)
                    )
            } else {
                ReservationButtonView(workoutClass: workoutClassVM.workoutClass)
            }
            
            
        }.padding()
            .navigationBarTitle(Text("\(workoutClassVM.workoutClass.time.components(separatedBy: " ")[0]) \(workoutClassVM.workoutClass.workoutType)"))
            .onAppear() {
                workoutClassVM.fetchIndividualWorkoutClassData(docId: docId, classDate: classDate)
            }
            .onDisappear() {
                workoutClassVM.detachWorkoutListener()
            }
        
    }
}

struct ReservationView_Previews: PreviewProvider {
    static var previews: some View {
        ReservationView(
            docId: "foo",
            classDate: Date()
        )
            .environmentObject(AuthViewModel())
            .environmentObject(WorkoutClassViewModel())
    }
}

struct ReservationButtonView: View {
    var workoutClass: WorkoutClass
    @EnvironmentObject var workoutClassVM: WorkoutClassViewModel
    @EnvironmentObject var authVM: AuthViewModel
    
    var body: some View {
        if workoutClassVM.isDisabled {
            ProgressView()
                .progressViewStyle(CircularProgressViewStyle(tint: Color("bruinGreenColor")))
        } else if checkIsReserved(uid: authVM.user?.uid ?? "", reservedUsers: workoutClass.reservedUsers ?? []) {
            Button(action: {
                workoutClassVM.isDisabled = true
                workoutClassVM.removeReservation(
                    documentId: workoutClass.id!,
                    classDate: workoutClass.classTimestamp,
                    uid: authVM.user?.uid ?? "")
                workoutClassVM.pollForReservationChange()
            }){
                Label(
                    title: { Text("Cancel Reservation")
                        .font(.title) },
                    icon: { Image(systemName: "person.badge.minus")
                        .font(.title) }
                )
                .padding()
                .frame(minWidth: /*@START_MENU_TOKEN@*/0/*@END_MENU_TOKEN@*/,  maxWidth: /*@START_MENU_TOKEN@*/.infinity/*@END_MENU_TOKEN@*/, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/)
                .background(LinearGradient(gradient: Gradient(colors: [Color.gray, Color("bruinGreenDarkColor")]), startPoint: .top, endPoint: .bottom))
                .cornerRadius(40)
                .foregroundColor(.white)
                .shadow(radius: 10)
            }.disabled(workoutClassVM.isDisabled)
        } else if workoutClass.reservationCnt == workoutClass.maxReservationCnt {
            Text("Class Full")
                .frame(minWidth: 0, maxWidth: .infinity)
                .font(.system(.title, design: .rounded))
                .padding()
                .foregroundColor(.gray)
                .overlay(
                    RoundedRectangle(cornerRadius: 25)
                        .stroke(Color.gray, lineWidth: 2)
                )
        } else{
            Button(action: {
                workoutClassVM.isDisabled = true
                workoutClassVM.addReservation(
                    documentId: workoutClass.id!,
                    classDate: workoutClass.classTimestamp,
                    reservedUserDetails: ["uid": authVM.user?.uid as Any, "photoURL": authVM.user?.photoURL?.absoluteString ?? "" as Any, "displayName": authVM.user?.displayName ?? "Bruin Fitness Member" as Any],
                    uid: authVM.user?.uid ?? "")
                workoutClassVM.pollForReservationChange()
                // TODO: Test when photoURL and displayName are empty
            }){
                // IOS 14+
                Label(
                    title: { Text("Reserve")
                        .font(.title) },
                    icon: { Image(systemName: "person.badge.plus")
                        .font(.title) }
                )
                .padding()
                .frame(minWidth: /*@START_MENU_TOKEN@*/0/*@END_MENU_TOKEN@*/,  maxWidth: /*@START_MENU_TOKEN@*/.infinity/*@END_MENU_TOKEN@*/, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/)
                .background(LinearGradient(gradient: Gradient(colors: [Color("bruinGreenColor"), Color("bruinGreenDarkColor")]), startPoint: .top, endPoint: .bottom))
                .cornerRadius(40)
                .foregroundColor(.white)
                .shadow(radius: 10)
            }
            .disabled(workoutClassVM.isDisabled)
        }
    }
}

func checkIsReserved(uid: String, reservedUsers: [reservedUser]) -> Bool {
  return reservedUsers.contains { $0.uid == uid }
}

