//
//  AllWorkoutsListView.swift
//  Werkout_ios
//
//  Created by Trey Tartt on 7/7/23.
//

import SwiftUI

struct AllWorkoutsListView: View {
    enum SortType: String, CaseIterable {
        case name = "Name"
        case date = "Date"
    }
    
    @State var searchString: String = ""
    @Binding var uniqueWorkoutUsers: [RegisteredUser]?
    @State private var filteredRegisterdUser: RegisteredUser?
    
    let workouts: [Workout]
    let selectedWorkout: ((Workout) -> Void)
    @State var filteredWorkouts = [Workout]()
    var refresh: (() -> Void)
    @State var currentSort: SortType?
    
    var body: some View {
        VStack {
            if let filteredRegisterdUser = filteredRegisterdUser {
                Text((filteredRegisterdUser.firstName ?? "NA") + "'s Workouts")
            }
            
            ScrollView {
                LazyVStack(spacing: 20) {
                    ForEach(filteredWorkouts, id:\.id) { workout in
                        WorkoutOverviewView(workout: workout)
                            .padding([.leading, .trailing])
                            .contentShape(Rectangle())
                            .onTapGesture {
                                selectedWorkout(workout)
                            }
                    }
                }
            }
            .refreshable {
                refresh()
            }
            
            HStack {
                TextField("Filter" ,text: $searchString)
                    .padding()
                    .textFieldStyle(OvalTextFieldStyle())
                
                if let uniqueWorkoutUsers = uniqueWorkoutUsers {
                    Menu(content: {
                        ForEach(uniqueWorkoutUsers, id: \.self) { index in
                            Button(action: {
                                filteredRegisterdUser = index
                                filteredWorkouts = filterWorkouts()
                            }, label: {
                                Text((index.firstName ?? "") + " -" + (index.lastName ?? ""))
                            })
                        }
                        
                        Button(action: {
                            filteredRegisterdUser = nil
                            filteredWorkouts = filterWorkouts()
                        }, label: {
                            Text("All")
                        })
                            
                    }, label: {
                        Image(systemName: filteredRegisterdUser == nil ? "person.2" : "person.2.fill")
                            .padding(.trailing)
                    })
                }
                
                Menu(content: {
                    ForEach(SortType.allCases, id: \.self) { index in
                        Button(action: {
                            sortWorkouts(sortType: index)
                        }, label: {
                            Text(index.rawValue)
                        })
                    }
                }, label: {
                    Image(systemName: "list.number")
                        .padding(.trailing)
                })
            }
        }
        .onChange(of: searchString) { newValue in
            filteredWorkouts = filterWorkouts()
        }
        .onAppear{
            filteredWorkouts = filterWorkouts()
        }
    }
    
    func sortWorkouts(sortType: SortType) {
        if currentSort == sortType {
            filteredWorkouts = filteredWorkouts.reversed()
            return
        }
        switch sortType {
        case .name:
            filteredWorkouts = filteredWorkouts.sorted(by: {
                $0.name < $1.name
            })
        case .date:
            filteredWorkouts = filteredWorkouts.sorted(by: {
                $0.createdAt ?? Date() < $1.createdAt ?? Date()
            })
        }
        currentSort = sortType
    }
    
    func filterWorkouts() -> [Workout] {
        var matchingWorkouts = [Workout]()
        
        if (!searchString.isEmpty && searchString.count > 0) {
            matchingWorkouts = workouts.filter({
                if $0.name.lowercased().contains(searchString.lowercased()) {
                    return true
                }
                
                if let equipment = $0.equipment?.joined(separator: "").lowercased(),
                   equipment.contains(searchString.lowercased()) {
                    return true
                }
                
                if let muscles = $0.muscles?.joined(separator: "").lowercased(),
                   muscles.contains(searchString.lowercased()) {
                    return true
                }

                return false
            })
        }
        
        if matchingWorkouts.isEmpty {
            matchingWorkouts.append(contentsOf: workouts)
        }
        
        if let filteredRegisterdUser = filteredRegisterdUser {
            matchingWorkouts = matchingWorkouts.filter({
                $0.registeredUser == filteredRegisterdUser
            })
        }

        return matchingWorkouts
    }
}

struct AllWorkoutsListView_Previews: PreviewProvider {
    static var previews: some View {
        AllWorkoutsListView(uniqueWorkoutUsers: .constant([]),
                            workouts: PreviewData.allWorkouts(),
                            selectedWorkout: { workout in },
                            refresh: {  })
    }
}
