//
//  GroupStageTeamView.swift
//  PadelClub
//
//  Created by Razmig Sarkissian on 03/04/2024.
//

import SwiftUI
import LeStorage

struct GroupStageTeamView: View {
    
    @EnvironmentObject var dataStore: DataStore
    @Environment(Tournament.self) var tournament: Tournament
    @EnvironmentObject var networkMonitor: NetworkMonitor

    @Environment(\.dismiss) private var dismiss
    
    @State private var contactType: ContactType? = nil
    @State private var sentError: ContactManagerError? = nil
    @State private var showSubscriptionView: Bool = false

    let groupStage: GroupStage
    var team: TeamRegistration
    
    var tournamentStore: TournamentStore {
        return self.tournament.tournamentStore
    }
    
    var messageSentFailed: Binding<Bool> {
        Binding {
            sentError != nil
        } set: { newValue in
            if newValue == false {
                sentError = nil
            }
        }
    }
    
    var body: some View {
        List {
            Section {
                ForEach(team.players()) { player in
                    EditablePlayerView(player: player, editingOptions: [.licenceId, .name, .payment])
                        .environmentObject(tournament.tournamentStore)
                }
            }

            if groupStage.tournamentObject()?.hasEnded() == false {
                if team.qualified == false {
                    Section {
                        NavigationLink {
                            GroupStageTeamReplacementView(team: team)
                        } label: {
                            Text("Chercher à remplacer")
                        }
                    }
                }
                
                Section {
                    if team.qualified == false {
                        RowButtonView("Qualifier l'équipe", role: .destructive) {
                            team.qualified = true
                            //team.bracketPosition = nil
                            _save()
                        }
                    } else {
                        RowButtonView("Annuler la qualification", role: .destructive) {
                            team.qualified = false
                            groupStage.tournamentObject()?.resetTeamScores(in: team.bracketPosition)
                            team.bracketPosition = nil
                            _save()
                        }
                    }
                }
                
                if team.qualified == false {
                    Section {
                        RowButtonView("Retirer de la poule", role: .destructive) {
                            team.groupStagePosition = nil
                            team.groupStage = nil
                            _save()
                            groupStage._matches().forEach({ $0.updateTeamScores() })
                        }
                    }
                }
            }
        }
        .toolbar {
            ToolbarItem(placement: .topBarTrailing) {
                MenuWarningView(tournament: tournament, teams: [team], contactType: $contactType)
            }
        }
        .alert("Un problème est survenu", isPresented: messageSentFailed) {
            Button("OK") {
            }
        } message: {
            Text(_networkErrorMessage)
        }
        .sheet(item: $contactType) { contactType in
            Group {
                switch contactType {
                case .message(_, let recipients, let body, _):
                    if Guard.main.paymentForNewTournament() != nil {
                        MessageComposeView(recipients: recipients, body: body) { result in
                            switch result {
                            case .cancelled:
                                break
                            case .failed:
                                self.sentError = .messageFailed
                            case .sent:
                                if networkMonitor.connected == false {
                                    self.sentError = .messageNotSent
                                }
                            @unknown default:
                                break
                            }
                        }
                    } else {
                        SubscriptionView(isPresented: self.$showSubscriptionView, showLackOfPlanMessage: true)
                            .environment(\.colorScheme, .light)
                    }
                case .mail(_, let recipients, let bccRecipients, let body, let subject, _):
                    if Guard.main.paymentForNewTournament() != nil {
                        MailComposeView(recipients: recipients, bccRecipients: bccRecipients, body: body, subject: subject) { result in
                            switch result {
                            case .cancelled, .saved:
                                self.contactType = nil
                            case .failed:
                                self.contactType = nil
                                self.sentError = .mailFailed
                            case .sent:
                                if networkMonitor.connected == false {
                                    self.contactType = nil
                                    self.sentError = .mailNotSent
                                }
                            @unknown default:
                                break
                            }
                        }
                    } else {
                        SubscriptionView(isPresented: self.$showSubscriptionView, showLackOfPlanMessage: true)
                            .environment(\.colorScheme, .light)
                    }
                }
            }
            .tint(.master)
        }


        .toolbarBackground(.visible, for: .navigationBar)
        .navigationTitle("Détail de l'équipe")
    }
    
    private var _networkErrorMessage: String {
        var errors: [String] = []
        
        if networkMonitor.connected == false {
            errors.append("L'appareil n'est pas connecté à internet.")
        }
        if sentError == .mailNotSent {
            errors.append("Le mail est dans la boîte d'envoi de l'app Mail. Vérifiez son état dans l'app Mail avant d'essayer de le renvoyer.")
        }
        if (sentError == .messageFailed || sentError == .messageNotSent) {
            errors.append("Le SMS n'a pas été envoyé")
        }
        if sentError == .mailFailed {
            errors.append("Le mail n'a pas été envoyé")
        }
        return errors.joined(separator: "\n")
    }

    private func _save() {
        do {
            try tournamentStore.teamRegistrations.addOrUpdate(instance: team)
        } catch {
            Logger.error(error)
        }
        dismiss()
    }
}
