//
//  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

    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
            _buildView(build, existingTournament: event?.existingBuild(build))
        }
    }
    
    var teamCount: Int? {
        if let tournament = tournament as? Tournament {
            let hasStarted = tournament.inscriptionClosed() || tournament.hasStarted()
            let count = hasStarted ? tournament.selectedSortedTeams().count : tournament.unsortedTeamsWithoutWO().count
            return count
        } else {
            return nil
        }
    }
    
    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 {
                    HStack {
                        Text(tournament.locationLabel(displayStyle)).lineLimit(1)
                            .font(.caption)
                        Spacer()
                        if tournament.isPrivate {
                            Text("privé").foregroundStyle(.logoRed)
                        }
                    }
                } else {
                    Text(tournament.clubLabel()).lineLimit(1)
                        .font(.caption)
                }
                HStack(alignment: .bottom) {
                    Text(build.level.localizedLabel())
                        .fontWeight(.semibold)
                    if displayStyle == .wide {
                        VStack(alignment: .leading, spacing: 0) {
                            Text(build.category.localizedLabel())
                            Text(build.age.localizedLabel())
                        }
                        .font(.caption)
                    }
                    Spacer()
                    if let tournament = tournament as? Tournament, displayStyle == .wide {
                        if tournament.isCanceled {
                            Text("Annulé").foregroundStyle(.logoRed)
                        } else if let teamCount {
                            Text(teamCount.formatted())
                        }
                    } else if let federalTournament = tournament as? FederalTournament {
                        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)
                                .tint(existingTournament != nil ? Color.green : nil)
                        }
                    }
                }
                .font(displayStyle == .wide ? .title : .title3)
                
                if displayStyle == .wide {
                    HStack {
                        Text(tournament.durationLabel())
                        Spacer()
                        if let tournament = tournament as? Tournament, tournament.isCanceled == false, let teamCount {
                            let hasStarted = tournament.inscriptionClosed() || tournament.hasStarted()
                            let word = hasStarted ? "équipe" : "inscription"
                            Text(word + teamCount.pluralSuffix)
                        }
                    }
                    Text(tournament.subtitleLabel()).lineLimit(1)
                } else {
                    Text(build.category.localizedLabel())
                    Text(build.age.localizedLabel())
                }
            }
        }
        .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())
//}
