//
//  DrawLogsView.swift
//  PadelClub
//
//  Created by razmig on 22/10/2024.
//

import SwiftUI
import LeStorage

struct DrawLogsView: View {
    @Environment(Tournament.self) var tournament
    
    var drawLogs: [DrawLog] {
        tournament.drawLogs().reversed()
    }

    var body: some View {
        List {
            ForEach(drawLogs) { drawLog in
                HStack {
                    VStack(alignment: .leading) {
                        Text(drawLog.localizedDrawSeedLabel())
                        Text(drawLog.drawDate.localizedDate())
                            .font(.footnote)
                            .foregroundStyle(.secondary)
                    }
                    Spacer()
                    VStack(alignment: .trailing) {
                        Text(drawLog.positionLabel()).lineLimit(1).truncationMode(.middle)
                        Text(drawLog.localizedDrawBranch())
                            .font(.footnote)
                            .foregroundStyle(.secondary)
                    }
                }
            }
        }
        .overlay(content: {
            if drawLogs.isEmpty {
                ContentUnavailableView("Aucun tirage", systemImage: "dice", description: Text("Aucun tirage au sort n'a été effectué."))
            }
        })
        .toolbar(content: {
            ToolbarItem(placement: .topBarTrailing) {
                Menu {
                    ShareLink(item: tournament.exportedDrawLogs()) {
                        Label("Partager les tirages", systemImage: "square.and.arrow.up")
                            .labelStyle(.titleAndIcon)
                    }
                    
                    Divider()
                    
                    Button("Tout effacer", role: .destructive) {
                        do {
                            try tournament.tournamentStore?.drawLogs.deleteAll()
                        } catch {
                            Logger.error(error)
                        }
                    }
                } label: {
                    LabelOptions()
                }
            }
        })
        .navigationBarTitleDisplayMode(.inline)
        .toolbarBackground(.visible, for: .navigationBar)
        .navigationTitle("Journal des tirages")
    }
}
