using System.Diagnostics;
using System.Threading.Tasks;
using System.Windows.Input;
using WorkFlowCheck.Common.DTO;
using WorkFlowCheck.MAUI.Pages.NFC;
using WorkFlowCheck.MAUI.Services.Interfaces;

namespace WorkFlowCheck.MAUI.Pages.CheckList;

public partial class CheckListPage : ContentPage
{
    private readonly ICheckListService _checkListService;
    private readonly IUserService _userService;
    private bool _isLoading;


    public ICommand NewCommand { get; set; }
    public ICommand ContinueCommand { get; set; }
    public bool IsLoading
    {
        get => _isLoading;
        set
        {
            _isLoading = value;
            OnPropertyChanged(nameof(IsLoading));
        }
    }


    public CheckListPage()
    {
        InitializeComponent();
        _checkListService = MauiProgram.ServiceProvider.GetRequiredService<ICheckListService>();
        _userService = MauiProgram.ServiceProvider.GetRequiredService<IUserService>();
        NewCommand = new Command<CheckListTemplateHeaderDTO>(OnNewItem);
        ContinueCommand = new Command<CheckListHeaderDTO>(OnContinueItem);

    }
    protected override bool OnBackButtonPressed()
    {
        Shell.Current.GoToAsync("//MainPage");
        return true;
    }
    protected override async void OnAppearing()
    {
        base.OnAppearing();

        BindingContext = this;
        await LoadCheckListTemplate();
        await LoadCheckList();
    }
    private async void OnNewItem(CheckListTemplateHeaderDTO checkListTemplateHeaderDTO)
    {
        IsLoading = true;
        await _checkListService.StartNew(
            new CheckListHeaderNewDTO() 
            { 
                UserId = _userService.GetCurrentUser().Id,
                CheckListTemplateHeaderId = checkListTemplateHeaderDTO.Id
            });
        IsLoading = false;
    }
    private async void OnContinueItem(CheckListHeaderDTO checkListHeaderDTO)
    {
        var checkPointCode = await NFCWaiter.ShowModalAsync();
        if (!string.IsNullOrEmpty(checkPointCode))
        {
            if (Navigation.ModalStack.Count > 0)
            {
                await Navigation.PopModalAsync();
            }

            await Navigation.PushAsync(new CheckListWorkPage(checkListHeaderDTO.Id, checkPointCode));
        }
    }
    private async Task LoadCheckListTemplate()
    {
        IsLoading = true;
        var userId = _userService.GetCurrentUser()?.Id;
        CheckListTemplate.ItemsSource = await _checkListService.GetCheckListTemplates(userId ?? 1);
        IsLoading = false;
    }
    private async Task LoadCheckList()
    {
        IsLoading = true;
        var userId = _userService.GetCurrentUser()?.Id;
        CheckList.ItemsSource = await _checkListService.GetCheckLists(userId ?? 1);
        IsLoading = false;
    }

}