//
//  UserSearchView.swift
//  PadelClub
//
//  Created by Laurent Morvillier on 03/12/2024.
//

import Combine
import LeStorage
import SwiftUI

class UserSearchViewModel: ObservableObject {
    
    @Published var searchText = ""
    @Published var userNames: [ShortUser] = []
    
    @Published var users: [String] = []
    @Published var availableUsers: [ShortUser] = []
    @Published var selectedUsers: [String] = []

    init() {
        Task {
            do {
                let service = try StoreCenter.main.service()
                let userNames = try await service.getUserNames()
                DispatchQueue.main.async {
                    self.userNames = userNames
                    self.availableUsers = self.users.compactMap { userId in
                        self.userNames.first(where: { $0.id == userId })
                    }
                }
            } catch {
                Logger.error(error)
            }
        }
    }
    
    func userTapped(_ user: String) {
        if let index = self.selectedUsers.firstIndex(of: user) {
            self.selectedUsers.remove(at: index)
        } else {
            self.selectedUsers.append(user)
        }
    }
    
    func contains(_ user: String) -> Bool {
        return self.selectedUsers.firstIndex(of: user) != nil
    }
}

struct ShareModelView<T: SyncedStorable> : View {
    @StateObject private var viewModel = UserSearchViewModel()

    let instance: T
    
    var body: some View {
        NavigationView {
            if !self.viewModel.availableUsers.isEmpty {
                List {
                    ForEach(self.viewModel.availableUsers, id: \.id) { user in
                        let isSelected = viewModel.contains(user.id)
                        UserRow(user: user, isSelected: isSelected)
                            .contentShape(Rectangle())
                            .onTapGesture {
                                self.viewModel.userTapped(user.id)
                                self._modifyAuthorizedUsersList()
                            }
                    }
                }
                .listStyle(PlainListStyle())
                .navigationTitle("Partage")
            } else {
                ContentUnavailableView("Si vous souhaitez partager votre tournoi avec d'autres utilisateurs, veuillez contacter notre support", image: "person.crop.circle.badge.xmark")
            }
            
        }.onAppear {
            self.viewModel.selectedUsers = StoreCenter.main.authorizedUsers(for: self.instance.stringId)
            self.viewModel.users = DataStore.shared.user.agents
        }
    }

    fileprivate func _modifyAuthorizedUsersList() {
        do {
            try StoreCenter.main.setAuthorizedUsers(for: self.instance, users: self.viewModel.selectedUsers)
        } catch {
            Logger.error(error)
        }

    }
}

struct UserRow: View {
    let user: ShortUser
    let isSelected: Bool

    var body: some View {
        HStack {
            Text("\(user.firstName) \(user.lastName)")
            Spacer()
            if self.isSelected {
                Image(systemName: "checkmark").foregroundStyle(.logoOrange)
            }
        }
        .padding(.vertical, 4)
    }
}

// Preview provider
struct ShareModelView_Previews: PreviewProvider {
    static var previews: some View {
        ShareModelView(instance: Tournament.fake())
    }
}
