//
//  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
            }
        }
    }
    
    private func _editingOptions() -> [EditablePlayerView.PlayerEditingOption] {
        if tournament.isFree() {
            return [.licenceId, .name, .presence]
        } else {
            return [.licenceId, .name, .payment]
        }
    }
    
    var body: some View {
        List {
            Section {
                if let name = team.name, name.isEmpty == false {
                    Text(name).foregroundStyle(.secondary)
                }
                ForEach(team.players()) { player in
                    EditablePlayerView(player: player, editingOptions: _editingOptions())
                }
            } footer: {
                NavigationLink {
                    EditingTeamView(team: team)
                        .environment(tournament)
                } label: {
                    Text("détails de l'équipe")
                        .underline()
                }
            }

            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 groupStage.tournamentObject()?.hasEnded() == false {
                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.contactType = nil
                                    if team.getPhoneNumbers().isEmpty == false {
                                        self.sentError = .uncalledTeams([team])
                                    } else {
                                        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
                                    if team.getMail().isEmpty == false {
                                        self.sentError = .uncalledTeams([team])
                                    } else {
                                        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 {
        ContactManagerError.getNetworkErrorMessage(sentError: sentError, networkMonitorConnected: networkMonitor.connected)
    }

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