//
//  MenuWarningView.swift
//  PadelClub
//
//  Created by razmig on 28/04/2024.
//

import SwiftUI
import LeStorage

struct MenuWarningView: View {
    let tournament: Tournament
    let teams: [TeamRegistration]
    var date: Date?
    var message: String?
    var umpireMail: String?
    var subject: String?
    
    @Binding var contactType: ContactType?

    @State var showSubscriptionView: Bool = false
    @State var showUserCreationView: Bool = false

    @State var savedContactType: ContactType? = nil
    
    private func _getUmpireMail() -> [String]? {
        if let umpireMail {
            return [umpireMail]
        }
        return nil
    }
    
    var body: some View {
        
        Menu {
            if let team = teams.first, teams.count == 1 {
                _teamActionView(team)
            } else {
                Menu("Tout le monde") {
                    let players = teams.flatMap({ $0.players() })
                    _actionView(players: players, privateMode: true)
                }
                Divider()
                ForEach(teams) { team in
                    _teamView(team)
                }
            }
        } label: {
            Text("Prévenir")
                .underline()
        }
        .sheet(isPresented: self.$showSubscriptionView, content: {
            NavigationStack {
                SubscriptionView(isPresented: self.$showSubscriptionView, showLackOfPlanMessage: true)
            }
        })
        .sheet(isPresented: self.$showUserCreationView, content: {
            NavigationStack {
                LoginView(reason: LoginReason.loginRequiredForFeature) { _ in
                    self.showUserCreationView = false
                    self._tryToContact()
                }
            }
        })
    }
    
    @ViewBuilder
    private func _actionView(players: [PlayerRegistration], privateMode: Bool = false) -> some View {
        if players.count == 1, let player = players.first, let number = player.phoneNumber?.replacingOccurrences(of: " ", with: ""), let url = URL(string: "tel:\(number)") {
            Link(destination: url) {
                Label("Appeler", systemImage: "phone")
                Text(number)
            }
        } else {
            Menu {
                ForEach(players) { player in
                    if let number = player.phoneNumber?.replacingOccurrences(of: " ", with: ""), let url = URL(string: "tel:\(number)") {
                        Link(destination: url) {
                            Label(player.playerLabel(.short), systemImage: "phone")
                            Text(number)
                        }
                    }
                }
            } label: {
                Text("Appeler un joueur")
            }
        }

        Button("Message") {
            self._contactByMessage(players: players, privateMode: privateMode)
        }
        Button("Mail") {
            self._contactByMail(players: players, privateMode: privateMode)
        }
    }
    
    fileprivate func _contactByMessage(players: [PlayerRegistration], privateMode: Bool) {
        self.savedContactType = .message(date: date, recipients: players.compactMap({ $0.phoneNumber }), body: message, tournamentBuild: nil)
        self._tryToContact()
    }
    
    fileprivate func _contactByMail(players: [PlayerRegistration], privateMode: Bool) {
        self.savedContactType = .mail(date: date, recipients: privateMode ? _getUmpireMail() : players.compactMap({ $0.email }), bccRecipients: privateMode ? players.compactMap({ $0.email }) : nil, body: message, subject: subject, tournamentBuild: nil)
        self._tryToContact()
    }
    
    func _playerView(_ player: PlayerRegistration) -> some View {
        Menu {
            let players = [player]
            _actionView(players: players)
        } label: {
            Text(player.playerLabel())
        }
    }

    func _teamView(_ team: TeamRegistration) -> some View {
        Menu {
            _teamActionView(team)
        } label: {
            Text(team.teamLabel(.short, twoLines: true))
        }
    }
    
    @ViewBuilder
    func _teamActionView(_ team: TeamRegistration) -> some View {
        Menu("Toute l'équipe") {
            let players = team.players()
            _actionView(players: players)
        }
        Divider()
        ForEach(team.players()) { player in
            _playerView(player)
        }
    }
    
    fileprivate func _tryToContact() {
        self._verifyUser {
            self._payTournamentAndExecute {
                self.contactType = self.savedContactType
            }
        }
    }
    
    fileprivate func _verifyUser(_ handler: () -> ()) {
        if StoreCenter.main.userId != nil {
            handler()
        } else {
            self.showUserCreationView = true
        }
    }
    
    fileprivate func _payTournamentAndExecute(_ handler: () -> ()) {
        do {
            try tournament.payIfNecessary()
            handler()
        } catch {
            self.showSubscriptionView = true
        }
    }
    
}

//#Preview {
//    MenuWarningView(teams: [], contactType: .constant(nil))
//}
