using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using WK5.Core;
using WK5.Core.Basis.Filter;
using WK5.Core.Models;
using WK5.Core.PageModels;
using WK5_Blazor.CoreExtensions;

namespace WK5_Blazor.Pages.Bestellungen
{
    public partial class BestellÜbersicht : IHasPageFilter, IAsyncDisposable, IHilfeModal
    {

        public BestellungFilter Filter { get; set; } = new BestellungFilter() { Limit = 30 };
        private int _selectedLieferantenId;
        private bool _showLieferantenKontakte;

        [Parameter] public int Seite { get => _seite; set => _seite = value <= 0 ? 1 : value; }
        public int TotalItems { get; set; }

        private List<Bestellung> _bestellungen = new List<Bestellung>();
        private CancellationTokenSource _cts = new CancellationTokenSource();

        public Bestellung? SelectedBestellung { get; set; }
        public bool ShowHilfeModal { get; set; }

        private int _seite;


        public const string LocalStorageFilterKey = "BestellÜbersicht.Filter";

        protected override async Task OnInitializedAsync()
        {
            await SetAlerts();
        }

        private Task ShowLieferantenKontakte(int lieferantenId)
        {
            _selectedLieferantenId = lieferantenId;
            _showLieferantenKontakte = true;
            return Task.CompletedTask;
        }
        private Task OnBestellungSelectedAsync(Bestellung bestellung)
        {
            if (SelectedBestellung == bestellung)
            {
                SelectedBestellung = null;
            }
            else
            {
                SelectedBestellung = bestellung;
            }
            return Task.CompletedTask;
        }

        protected override async Task OnParametersSetAsync()
        {
            var localStorageResult = await LocalStorage.GetAsync<BestellungFilter>(LocalStorageFilterKey);
            if (localStorageResult.Success)
            {
                if (localStorageResult.Value is not null)
                {
                    Filter = localStorageResult.Value;
                }
            }

            Filter.Seite = Seite;
            await LadeBestellungen();
        }


        private async Task LadeBestellungen()
        {
            _cts.Cancel();
            _cts = new CancellationTokenSource();
            _bestellungen.Clear();
            var token = _cts.Token;
            SelectedBestellung = null;
            await LocalStorage.SetAsync(LocalStorageFilterKey, Filter);
            using FbController2 fbController = new FbController2();
            try
            {
                await foreach (var bestellung in bestellService.GetBestellungenAsync(Filter, fbController, token))
                {
                    _bestellungen.Add(bestellung);
                    StateHasChanged();
                }
                TotalItems = await bestellService.GetAnzahlBestellungenAsync(Filter, fbController, token);
            }
            catch (OperationCanceledException){}
            catch (Exception)
            {
                Filter = new BestellungFilter() { Limit = 30 };
                await LocalStorage.SetAsync(LocalStorageFilterKey, Filter);
                throw;
            }
        }

        private string GetRowClass(Bestellung bestellung)
        {
            if(bestellung.BEST_L_ERLEDIGT)
            {
                return "table-success";
            }

            if(bestellung.BEST_D_LIEFTERMIN > DateTime.Today.Date)
            {
                return "table-warning";
            }

            return "table-danger";
        }

        public override ValueTask DisposeAsync()
        {
            _cts?.Cancel();
            _cts?.Dispose();
            return base.DisposeAsync();
        }
    }
}
