//
//  TournamentCellView.swift
//  PadelClub
//
//  Created by Razmig Sarkissian on 29/02/2024.
//

import SwiftUI
import LeStorage

struct TournamentCellView: View {
    @EnvironmentObject var dataStore: DataStore
    @Environment(NavigationViewModel.self) private var navigation

    let tournament: FederalTournamentHolder
//    let color: Color = .black
    var displayStyle: DisplayStyle = .wide
    @State var shouldTournamentBeOver: Bool = false

    var event: Event? {
        guard let federalTournament = tournament as? FederalTournament else { return nil }
        return dataStore.events.first(where: { $0.tenupId == federalTournament.id.string })
    }

    var body: some View {
        ForEach(tournament.tournaments, id: \.id) { build in
            if let federalTournament = tournament as? FederalTournament {
                if FederalDataViewModel.shared.isFederalTournamentValidForFilters(federalTournament, build: build) {
                    if navigation.agendaDestination == .around {
                        NavigationLink {
                            TournamentSubscriptionView(federalTournament: federalTournament, build: build, user: dataStore.user)
                        } label: {
                            _buildView(build, existingTournament: event?.existingBuild(build))
                        }
                    } else {
                        _buildView(build, existingTournament: event?.existingBuild(build))
                    }
                }
            } else {
                _buildView(build, existingTournament: event?.existingBuild(build))
            }
        }
        .id(shouldTournamentBeOver)
    }
    
    var teamCount: Int? {
        guard let tournament = tournament as? Tournament, DataStore.shared.tournaments.contains(where: {$0.id == self.tournament.holderId }) else { // we make sure the tournament is in the DataStore otherwise we keep instantiating TournamentStore after disconnections
            return nil
        }
        
        let hasStarted = tournament.inscriptionClosed() || tournament.hasStarted()
        let count = hasStarted ? tournament.selectedSortedTeams().count : tournament.unsortedTeamsWithoutWO().count
        return count
    }
    
    fileprivate func _spacing() -> CGFloat {
        self.displayStyle == .short ? 8.0 : 16.0
    }
    
    private func _buildView(_ build: any TournamentBuildHolder, existingTournament: Tournament?) -> some View {
        HStack(spacing: self._spacing()) {
            switch displayStyle {
            case .short:
                DateVerticalView(date: tournament.startDate)
            case .wide, .title:
                VStack(alignment: .center, spacing: -2.0) {
                    Text(tournament.startDate.formatted(.dateTime.weekday(.abbreviated)).uppercased())
                        .font(.system(size: 14.0)).fontWeight(.medium)
                    Text(tournament.startDate.formatted(.dateTime.day(.twoDigits)))
                        .font(.title).fontWeight(.semibold)
//                        .monospacedDigit()
                }
            }
//            DateBoxView(date: tournament.startDate, displayStyle: displayStyle == .wide ? .short : .wide)
//                .fontWeight(displayStyle == .wide ? .semibold : .regular)
//            Rectangle()
//                .fill(Color(white: 0.8))
//                .frame(width: 2)
            VStack(alignment: .leading, spacing: 0.0) {
                if let tournament = tournament as? Tournament {
#if targetEnvironment(simulator)
                    Text(tournament.id)
#endif

                    HStack {
                        Text(tournament.locationLabel(displayStyle))
                            .lineLimit(1)
                            .truncationMode(.tail)
                            .font(.caption)
                        Spacer()
                        if tournament.isPrivate {
                            if displayStyle == .short {
                                Text("privé")
                            } else {
                                Text("privé")
                                    .capsule(foreground: .black, background: .beige)
                            }
                        }
                    }
                } else {
                    Text(tournament.clubLabel()).lineLimit(1)
                        .font(.caption)
                }
                HStack(alignment: .bottom) {
                    Text(tournament.tournamentTitle(displayStyle, forBuild: build))
                        .fontWeight(.semibold)
                        .lineLimit(1)
                        .truncationMode(.tail)
                    if displayStyle == .wide, tournament.displayAgeAndCategory(forBuild: build) {
                        VStack(alignment: .leading, spacing: 0) {
                            Text(build.category.localizedLabel())
                            Text(build.age.localizedFederalAgeLabel())
                        }
                        .font(.caption)
                    }
                    Spacer()
                    if let tournament = tournament as? Tournament, displayStyle == .wide {
                        if tournament.refreshInProgress || tournament.refreshRanking {
                            ProgressView()
                        } else if tournament.isCanceled {
                            Text("Annulé".uppercased())
                                .capsule(foreground: .white, background: .logoRed)
                        } else if shouldTournamentBeOver {
                            Image(systemName: "clock.badge.questionmark").foregroundStyle(.logoRed)
                        } else if let teamCount {
                            Text(teamCount.formatted())
                        }
                    } else if let federalTournament = tournament as? FederalTournament, navigation.agendaDestination != .around {
                        Button {
                            _createOrShow(federalTournament: federalTournament, existingTournament: existingTournament, build: build)
                        } label: {
                            Image(systemName: existingTournament != nil ? "checkmark.circle.fill" : "square.and.arrow.down")
                                .resizable()
                                .scaledToFit()
                                .frame(height: 28)
                                .accessibilityLabel("importer ou ouvrir")
                                .tint(existingTournament != nil ? Color.green : nil)
                        }
                    }
                }
                .font(displayStyle == .wide ? .title : .title3)
                
                if displayStyle == .wide {
                    HStack(alignment: .top) {
                        VStack(alignment: .leading) {
                            let sub = tournament.subtitleLabel(forBuild: build)
                            if sub.isEmpty == false {
                                Text(sub)
                                    .lineLimit(1)
                                    .truncationMode(.tail)
                            }
                            Text(tournament.durationLabel())
                        }
                        Spacer()
                        if let tournament = tournament as? Tournament, tournament.isCanceled == false {
                            if shouldTournamentBeOver {
                                Text("à clôturer ?")
                                    .foregroundStyle(.logoRed)
                            } else if let teamCount {
                                let hasStarted = tournament.inscriptionClosed() || tournament.hasStarted()
                                let word = hasStarted ? "équipe" : "inscription"
                                Text(word + teamCount.pluralSuffix)
                                    .task(priority: .background) {
                                        self.shouldTournamentBeOver = await tournament.shouldTournamentBeOver()
                                    }
                            }
                        }
                    }
                } else {
                    Text(build.category.localizedLabel())
                    Text(build.age.localizedFederalAgeLabel())
                }
                if displayStyle == .wide, let tournament = tournament as? Tournament {
                    if tournament.enableOnlineRegistration {
                        let value: Int = tournament.onlineTeams().count
                        HStack {
                            Spacer()
                            if value > 0 {
                                Text("(dont " + value.formatted() + " inscrite\(value.pluralSuffix) en ligne)")
                            }
                        }
                    }
                }
            }
        }
        .font(.caption)
    }
    
    private func _createOrShow(federalTournament: FederalTournament, existingTournament: Tournament?, build: any TournamentBuildHolder) {
        if let existingTournament {
            navigation.agendaDestination = .activity
            navigation.path.append(existingTournament)
        } else {
            let event = federalTournament.getEvent()
            let newTournament = Tournament.newEmptyInstance()
            newTournament.event = event.id
            //todo
            //newTournament.umpireMail()
            //newTournament.jsonData = jsonData
            newTournament.tournamentLevel = build.level
            newTournament.tournamentCategory = build.category
            newTournament.federalTournamentAge = build.age
            newTournament.dayDuration = federalTournament.dayDuration
            newTournament.startDate = federalTournament.startDate.atBeginningOfDay(hourInt: 9)
            newTournament.setupFederalSettings()
            do {
                try dataStore.tournaments.addOrUpdate(instance: newTournament)
            } catch {
                Logger.error(error)
            }
        }
    }
}

//#Preview {
//    TournamentCellView(tournament: Tournament.fake())
//}
