//
//  MatchDateView.swift
//  Padel Tournament
//
//  Created by Razmig Sarkissian on 25/11/2023.
//

import SwiftUI
import LeStorage

struct MatchDateView: View {
    @EnvironmentObject var dataStore: DataStore
    var match: Match
    var showPrefix: Bool = false
    private var isReady: Bool
    private var hasWalkoutTeam: Bool
    private var hasEnded: Bool
    
    init(match: Match, showPrefix: Bool) {
        self.match = match
        self.showPrefix = showPrefix
        self.isReady = match.isReady()
        self.hasWalkoutTeam = match.hasWalkoutTeam()
        self.hasEnded = match.hasEnded()
    }
    
    var body: some View {
        Menu {
            let estimatedDuration = match.getDuration()
            if match.startDate == nil && isReady {
                Button("Démarrer") {
                    match.startDate = Date()
                    match.confirmed = true
                    _save()
                }
                Button("Démarrer dans 5 minutes") {
                    match.startDate = Calendar.current.date(byAdding: .minute, value: 5, to: Date())
                    match.confirmed = true
                    _save()
                }
                Button("Démarrer dans 15 minutes") {
                    match.startDate = Calendar.current.date(byAdding: .minute, value: 15, to: Date())
                    match.confirmed = true
                    _save()
                }
                Button("Démarrer dans \(estimatedDuration.formatted()) minutes") {
                    match.startDate = Calendar.current.date(byAdding: .minute, value: estimatedDuration, to: Date())
                    match.confirmed = true
                    _save()
                }
            } else {
                if isReady {
                    Button("Démarrer maintenant") {
                        match.startDate = Date()
                        match.endDate = nil
                        match.confirmed = true
                        _save()
                    }
                } else {
                    Button("Décaler de \(estimatedDuration) minutes") {
                        match.cleanScheduleAndSave(match.startDate?.addingTimeInterval(Double(estimatedDuration) * 60.0))
                    }
                }
                Button("Retirer l'horaire") {
                    match.cleanScheduleAndSave()
                }
            }
        } label: {
            label
        }
        .buttonStyle(.plain)
    }
    
    @ViewBuilder
    var label: some View {
        HStack {
            VStack(alignment: .trailing) {
                if hasWalkoutTeam == false {
                    if let startDate = match.startDate, match.endDate == nil {
                        if startDate.timeIntervalSinceNow < 0 {
                            if showPrefix {
                                Text("en cours").font(.footnote).foregroundStyle(.secondary)
                            }
                            if match.isReady() && match.confirmed {
                                Text(startDate, style: .timer)
                                    .monospacedDigit()
                                    .foregroundStyle(Color.master)
                                    .underline()
                            } else {
                                Text("en retard")
                                    .foregroundStyle(Color.master)
                                    .underline()
                            }
                        } else if startDate.timeIntervalSinceNow <= 7200 && showPrefix {
                            if showPrefix {
                                Text("démarre dans")
                                    .font(.footnote).foregroundStyle(.secondary)
                            }
                            Text(startDate, style: .timer)
                                .monospacedDigit()
                                .foregroundStyle(Color.master)
                                .underline()
                        } else {
                            if showPrefix {
                                Text("le " + startDate.formatted(date: .abbreviated, time: .omitted))
                                    .font(.footnote).foregroundStyle(.secondary)
                                Text("à " + startDate.formatted(date: .omitted, time: .shortened))
                                    .monospacedDigit()
                                    .foregroundStyle(Color.master)
                                    .underline()
                            } else {
                                Text(startDate.formatted(date: .abbreviated, time: .shortened))
                                    .monospacedDigit()
                                    .foregroundStyle(Color.master)
                                    .underline()
                            }
                        }
                    }
                    if let startDate = match.startDate, let endDate = match.endDate {
                        let duration = Duration(
                            secondsComponent: Int64(endDate.timeIntervalSince(startDate)),
                            attosecondsComponent: 0
                        ).formatted(.units(allowed: [.hours, .minutes], width: .narrow))
                        if showPrefix {
                            Text("durée").font(.footnote).foregroundStyle(.secondary)
                        }
                        Text(duration)
                            .monospacedDigit()
                            .foregroundStyle(Color.master)
                            .underline()
                    }
                    
                    if match.startDate == nil && hasEnded == false {
                        Text("démarrage").font(.footnote).foregroundStyle(.secondary)
                        Text("non défini")
                            .foregroundStyle(Color.master)
                            .underline()
                    }
                }
            }
        }
    }
    
    private func _save() {
        do {
            try dataStore.matches.addOrUpdate(instance: match)
        } catch {
            Logger.error(error)
        }
    }
}

