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

import SwiftUI
import LeStorage

struct MainView: View {
    @StateObject var dataStore = DataStore.shared
    @AppStorage("importingFiles") var importingFiles: Bool = false
    @Environment(NavigationViewModel.self) private var navigation: NavigationViewModel

    @State private var checkingFilesAttempt: Int = 0
    @State private var checkingFiles: Bool = false
    
    var lastDataSource: String? {
        dataStore.appSettings.lastDataSource
    }
    
    var selectedTabHandler: Binding<TabDestination?> { Binding(
        get: { navigation.selectedTab },
        set: {
            if $0 == navigation.selectedTab {
//                switch navigation.selectedTab {
//                case .activity:
//                    navigation.path.removeLast()
//                case .toolbox:
//                    navigation.toolboxPath = NavigationPath()
//                case .umpire:
//                    navigation.umpirePath = NavigationPath()
//                case .ongoing:
//                    navigation.ongoingPath = NavigationPath()
//                case .tournamentOrganizer:
//                    break
//                case .none:
//                    break
//                }
            } else {
                navigation.selectedTab = $0
            }
        }
    )}

    var matches: [Match] {
        return dataStore.matches.filter { match in
            match.confirmed && match.startDate != nil && match.endDate == nil && match.courtIndex != nil }
    }
    
    private func _isConnected() -> Bool {
        return Store.main.hasToken() && Store.main.userId != nil
    }

    var badgeText: Text? {
        return (Store.main.userName() != nil && _isConnected() == false) ? Text("!").font(.headline) : nil
    }

    var body: some View {
        TabView(selection: selectedTabHandler) {
            ActivityView()
                .tabItem(for: .activity)
                .onAppear {
                    if let lastDataSource, lastDataSource != URL.importDateFormatter.string(from: Date()), checkingFiles == false, importingFiles == false {
                        Task {
                            await self._checkSourceFileAvailability()
                        }
                    }
                }
            TournamentOrganizerView()
                .tabItem(for: .tournamentOrganizer)
            OngoingView()
                .tabItem(for: .ongoing)
                .badge(matches.count)
            ToolboxView()
                .tabItem(for: .toolbox)
            UmpireView()
                .tabItem(for: .umpire)
                .badge(badgeText)
//            PadelClubView()
//                .tabItem(for: .padelClub)
        }
        .id(dataStore.user.id)
        .onChange(of: dataStore.user.id) {
            navigation.path.removeLast(navigation.path.count)
        }
        .environmentObject(dataStore)
        .task {
            await self._checkSourceFileAvailability()
        }
//        .refreshable {
//            Task {
//                await self._checkSourceFileAvailability()
//            }
//        }
        .overlay(alignment: .bottom) {
            if importingFiles {
                _activityStatusBoxView()
            } else {
                _activityStatusBoxView()
                    .deferredRendering(for: .seconds(3))
            }
        }
    }
    
    func _activityStatusBoxView() -> some View {
        return _activityStatus()
            .toastFormatted()
    }
    
    @ViewBuilder
    func _activityStatus() -> some View {
        if importingFiles {
            HStack(spacing: 20) {
                ProgressView()
                if let mostRecentDateAvailable = SourceFileManager.shared.mostRecentDateAvailable {
                    if mostRecentDateAvailable > SourceFileManager.shared.lastDataSourceDate() ?? .distantPast {
                        Text("import " + mostRecentDateAvailable.monthYearFormatted)
                    }
                }
            }
        } else if let mostRecentDateAvailable = SourceFileManager.shared.mostRecentDateAvailable, let lastDataSourceDate = SourceFileManager.shared.lastDataSourceDate() {
            if mostRecentDateAvailable > lastDataSourceDate {
                Label(mostRecentDateAvailable.monthYearFormatted + " disponible", systemImage: "exclamationmark.triangle")
                    .labelStyle(.titleAndIcon)
            } else {
                Label(mostRecentDateAvailable.monthYearFormatted, systemImage: "checkmark")
                    .labelStyle(.titleAndIcon)
            }
        }
    }
    
    private func _checkSourceFileAvailability() async {
        print("dataStore.appSettings.lastDataSource :", dataStore.appSettings.lastDataSource ?? "none")
        print("check internet")
        print("check files on internet")
        print("check if any files on internet are more recent than here")
        checkingFiles = true
        await SourceFileManager.shared.fetchData()
        checkingFilesAttempt += 1
        checkingFiles = false
        
        if let mostRecentDateAvailable = SourceFileManager.shared.mostRecentDateAvailable, mostRecentDateAvailable > SourceFileManager.shared.lastDataSourceDate() ?? .distantPast {
            _startImporting()
        }
    }
    
    private func _startImporting() {
        importingFiles = true
        Task {
            let lastDataSource = await FileImportManager.shared.importDataFromFFT()
            dataStore.appSettings.lastDataSource = lastDataSource
            dataStore.appSettingsStorage.write()
            if let lastDataSource, let mostRecentDate = URL.importDateFormatter.date(from: lastDataSource) {
                await MonthData.calculateCurrentUnrankedValues(mostRecentDateAvailable: mostRecentDate)
            }
            importingFiles = false
            
            await _downloadPreviousDate()
        }
    }
        
    private func _downloadPreviousDate() async {
        await SourceFileManager.shared.getAllFiles(initialDate: "05-2024")
    }
}

//#Preview {
//    MainView()
//}
