using CommunityToolkit.Maui.Alerts;
using CommunityToolkit.Maui.Core;
using Plugin.NFC;
using System.Diagnostics;
using System.Globalization;
using System.Threading.Tasks;
using System.Windows.Input;
using WorkFlowCheck.Common.DTO;
using WorkFlowCheck.Common.Enums;
using WorkFlowCheck.MAUI.Helper;
using WorkFlowCheck.MAUI.Pages.NFC;
using WorkFlowCheck.MAUI.Pages.System;
using WorkFlowCheck.MAUI.Services.Interfaces;

namespace WorkFlowCheck.MAUI.Pages.CheckList;

public partial class CheckListPage : ContentPage
{
    private readonly ICheckListService _checkListService;
    private readonly IUserService _userService;
    private readonly ISyncService _syncService;
    private bool _isLoading;
    private bool _isNFCSupported;
    private UserDTO _currentUser;

    public ICommand NewCommand { get; set; }
    public ICommand ContinueCommand { get; set; }
    public ICommand UnblockCommand { get; set; }
    public ICommand BlockCommand { get; set; }
    public ICommand AcceptCommand { get; set; }
    public ICommand InfoCommand { get; set; }
    public ICommand CloseCommand { get; set; }
    public ICommand RefreshCommand { get; }
    public ICommand RefreshCommandT { get; }

    public bool IsLoading
    {
        get => _isLoading;
        set
        {
            _isLoading = value;
            OnPropertyChanged(nameof(IsLoading));
        }
    }
    public bool IsNFCSupported
    {
        get => _isNFCSupported;
        set
        {
            _isNFCSupported = value;
            OnPropertyChanged(nameof(IsNFCSupported));
        }
    }

    private bool _isRefreshing;
    private bool _isRefreshingT;
    public bool IsRefreshing
    {
        get => _isRefreshing;
        set
        {
            if (_isRefreshing != value)
            {
                _isRefreshing = value;
                OnPropertyChanged(nameof(IsRefreshing));
            }
        }
    }
    public bool IsRefreshingT
    {
        get => _isRefreshingT;
        set
        {
            if (_isRefreshingT != value)
            {
                _isRefreshingT = value;
                OnPropertyChanged(nameof(IsRefreshingT));
            }
        }
    }

    public CheckListPage()
    {
        InitializeComponent();
        _checkListService = MauiProgram.ServiceProvider.GetRequiredService<ICheckListService>();
        _userService = MauiProgram.ServiceProvider.GetRequiredService<IUserService>();
        _syncService = MauiProgram.ServiceProvider.GetRequiredService<ISyncService>();
        NewCommand = new Command<CheckListTemplateHeaderDTO>(OnNewItem);
        ContinueCommand = new Command<CheckListHeaderDTO>(OnContinueItem);
        UnblockCommand = new Command<CheckListHeaderDTO>(OnUnblockItem);
        BlockCommand = new Command<CheckListHeaderDTO>(OnBlockItem);
        AcceptCommand = new Command<CheckListHeaderDTO>(OnAcceptItem);
        InfoCommand = new Command<CheckListHeaderDTO>(OnInfoItem);
        CloseCommand = new Command<CheckListHeaderDTO>(OnCloseItem);
        RefreshCommand = new Command(async () => await OnRefresh());
        RefreshCommandT = new Command(async () => await OnRefreshT());

    }
    private async void OnSyncClicked(object sender, EventArgs e)
    {
        SyncBtn.IsEnabled = false;
        LoadingIndicator.IsRunning = true;
        LoadingIndicator.IsVisible = true;
        progressLabel.Text = "Szinkronizálás indítása...";
        progressBar.Progress = 0;

        try
        {
            await Task.Run(async () =>
            {
                await _syncService.SyncCheckListHeader_Down((percentage, infostring) =>
                {
                    // Direkt UI frissítés
                    MainThread.BeginInvokeOnMainThread(() =>
                    {
                        progressBar.Progress = percentage / 100;
                        progressLabel.Text = $"{infostring}: {percentage:0.00}%";
                    });
                });
            });
            SystemHelper.Syncronised = true;
            progressLabel.Text = "Szinkronizálás befejezve!";

        }
        catch (Exception ex)
        {
            progressLabel.Text = $"Hiba történt: {ex.Message}";
        }
        finally
        {
            SyncBtn.IsEnabled = true;
            LoadingIndicator.IsVisible = false;
            LoadingIndicator.IsRunning = false;
        }
    }
    private async Task OnRefresh()
    {
        IsRefreshing = true;

        //await _syncService.SyncCheckListHeader_Down((d, s) => { });

        await LoadCheckList();

        IsRefreshing = false;
    }
    private async Task OnRefreshT()
    {
        IsRefreshingT = true;

        //await _syncService.SyncCheckListHeader_Down((d, s) => { });

        await LoadCheckListTemplate();  

        IsRefreshingT = false;
    }
    private void SetInfo()
    {
        _currentUser = _userService.GetCurrentUser();
        DeviceId.Text = _userService.DeviceId;
        UserInfo.Text = $"{_currentUser?.LastName} {_currentUser?.FirstName}";
    }
    protected override bool OnBackButtonPressed()
    {
        Shell.Current.GoToAsync("//MainPage");
        return true;
    }
    protected override async void OnAppearing()
    {
        base.OnAppearing();
        BindingContext = this;
        //CrossNFC.Legacy = false;
        //IsNFCSupported = CrossNFC.IsSupported;
        SetInfo();
        await LoadCheckListTemplate();
        await LoadCheckList();
    }
    private async void OnNewItem(CheckListTemplateHeaderDTO checkListTemplateHeaderDTO)
    {
        bool answer = await DisplayAlert("Megerősítés", "Biztosan indítasz egy új ellenőrzést?", "Igen", "Mégsem");
        if (!answer) return;

        IsLoading = true;
        var response = await _checkListService.StartNew(
            new CheckListHeaderNewDTO()
            {
                UserId = _userService.GetCurrentUser().Id,
                CheckListTemplateHeaderId = checkListTemplateHeaderDTO.Id
            });
        IsLoading = false;

        if (response != null && response.IsSuccess)
        {
            await Task.Run(async () =>
            {
                await _syncService.SyncCheckListHeader_Down((percentage, infostring) =>
                {
                    // Direkt UI frissítés
                    MainThread.BeginInvokeOnMainThread(() =>
                    {
                        //progressBar.Progress = percentage / 100;
                        //progressLabel.Text = $"{infostring}: {percentage:0.00}%";
                    });
                });
            });
            await LoadCheckList();
            var visualOptions = new SnackbarOptions
            {
                ActionButtonTextColor = Colors.White,
                CornerRadius = new CornerRadius(10),
                Font = Microsoft.Maui.Font.SystemFontOfSize(16),
                BackgroundColor = Microsoft.Maui.Graphics.Color.Parse("Green"),
                TextColor = Colors.White

            };
            var snackbar = Snackbar.Make(
                                            $"Új ellenőrzés indult! {response.Data.DocumentNumber}",
                                            duration: TimeSpan.FromSeconds(10),
                                            action: () => Console.WriteLine("Snackbar dismissed"),
                                            actionButtonText: "OK",
                                            visualOptions: visualOptions
                                        );

            await snackbar.Show();
        }
    }
    private async void OnContinueItem(CheckListHeaderDTO checkListHeaderDTO)
    {
        if (CrossNFC.IsSupported && CrossNFC.Current.IsAvailable)
        {
            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));
            }
        }
        else
        {
            // Ha nincs NFC, akkor az utoljára beküldött és a sorrendben lévő checkpointra ugrik
            var nextCheckPoint = await _checkListService.GetNextCheckpointNotSend(checkListHeaderDTO);
            if (nextCheckPoint != null && nextCheckPoint.Id > 0)
            {
                if (!string.IsNullOrEmpty(nextCheckPoint.Code))
                {
                    if (Navigation.ModalStack.Count > 0)
                    {
                        await Navigation.PopModalAsync();
                    }

                    await Navigation.PushAsync(new CheckListWorkPage(checkListHeaderDTO.Id, nextCheckPoint.Code));
                }
            }

        }
    }
    private async void OnUnblockItem(CheckListHeaderDTO checkListHeaderDTO)
    {
        bool answer = await DisplayAlert("Megerősítés", "Biztosan feloldod a blokkolást?", "Igen", "Mégsem");
        if (answer)
        {
            var success = await _checkListService.UnBlockCheckListHeader(checkListHeaderDTO);
            if (success)
            {
                IsRefreshing = true;
                await LoadCheckList();
                IsRefreshing = false;
                await SystemHelper.ShowSnackBar("Blokkolás feloldás sikeres!",
                                                 SystemHelper.ColorToHex(Colors.Green),
                                                 SystemHelper.ColorToHex(Colors.Green),
                                                 SystemHelper.ColorToHex(Colors.White),
                                                 5);
            }
            else
            {

                await SystemHelper.ShowSnackBar("Blokkolás feloldás SIKERTELEN!",
                                                 SystemHelper.ColorToHex(Colors.Red),
                                                 SystemHelper.ColorToHex(Colors.Red),
                                                 SystemHelper.ColorToHex(Colors.Yellow),
                                                 15);
            }
        }
    }
    private async void OnBlockItem(CheckListHeaderDTO checkListHeaderDTO)
    {
        bool answer = await DisplayAlert("Megerősítés", "Biztosan blokkolod a folyamatot?", "Igen", "Mégsem");
        if (answer)
        {
            var success = await _checkListService.BlockCheckListHeader(checkListHeaderDTO);
            if (success)
            {
                IsRefreshing = true;
                await LoadCheckList();
                IsRefreshing = false;
                await SystemHelper.ShowSnackBar("Blokkolás sikeres!",
                                                 SystemHelper.ColorToHex(Colors.Green),
                                                 SystemHelper.ColorToHex(Colors.Green),
                                                 SystemHelper.ColorToHex(Colors.White),
                                                 5);
            }
            else
            {

                await SystemHelper.ShowSnackBar("Blokkolás SIKERTELEN!",
                                                 SystemHelper.ColorToHex(Colors.Red),
                                                 SystemHelper.ColorToHex(Colors.Red),
                                                 SystemHelper.ColorToHex(Colors.Yellow),
                                                 15);
            }
        }
    }
    private async void OnCloseItem(CheckListHeaderDTO checkListHeaderDTO)
    {
        var popup = new InputPopup("Kérem adja meg a lezárás okát!");
        var (isConfirmed, userInput) = await popup.ShowAsync();


        if (isConfirmed && !string.IsNullOrEmpty(userInput))
        {
            var checkListHeaderCloseDTO = new CheckListHeaderCloseDTO()
            {
                Id = checkListHeaderDTO.Id,
                CloseReason = userInput,
                UserId = _userService.GetCurrentUser().Id
            };
            var success = await _checkListService.CloseCheckListHeader(checkListHeaderCloseDTO);
            if (success)
            {
                IsRefreshing = true;
                await LoadCheckList();
                IsRefreshing = false;
                await SystemHelper.ShowSnackBar("Lezárás sikeres!",
                                                 SystemHelper.ColorToHex(Colors.Green),
                                                 SystemHelper.ColorToHex(Colors.Green),
                                                 SystemHelper.ColorToHex(Colors.White),
                                                 5);
            }
            else
            {

                await SystemHelper.ShowSnackBar("Lezárás SIKERTELEN!",
                                                 SystemHelper.ColorToHex(Colors.Red),
                                                 SystemHelper.ColorToHex(Colors.Red),
                                                 SystemHelper.ColorToHex(Colors.Yellow),
                                                 15);
            }
        }
    }
    private async void OnAcceptItem(CheckListHeaderDTO checkListHeaderDTO)
    {
        bool answer = await DisplayAlert("Megerősítés", "Biztosan jóváhagyod a folyamatot?", "Igen", "Mégsem");
        if (answer)
        {
            var success = await _checkListService.AcceptCheckListHeader(checkListHeaderDTO);
            if (success)
            {
                IsRefreshing = true;
                await LoadCheckList();
                IsRefreshing = false;
                await SystemHelper.ShowSnackBar("Jóváhagyás sikeres!",
                                                 SystemHelper.ColorToHex(Colors.Green),
                                                 SystemHelper.ColorToHex(Colors.Green),
                                                 SystemHelper.ColorToHex(Colors.White),
                                                 5);
            }
            else
            {

                await SystemHelper.ShowSnackBar("Jóváhagyás SIKERTELEN!",
                                                 SystemHelper.ColorToHex(Colors.Red),
                                                 SystemHelper.ColorToHex(Colors.Red),
                                                 SystemHelper.ColorToHex(Colors.Yellow),
                                                 15);
            }
        }
    }
    private async void OnInfoItem(CheckListHeaderDTO checkListHeaderDTO)
    {
        await Navigation.PushAsync(new CheckListInfoPage(checkListHeaderDTO));
    }
    private async Task LoadCheckListTemplate()
    {
        IsLoading = true;

        CheckListTemplate.ItemsSource = await _checkListService.GetCheckListTemplates(_currentUser.Id);
        IsLoading = false;
    }
    private async Task LoadCheckList()
    {
        IsLoading = true;

        var checkListHeaderDTOs = await _checkListService.GetCheckLists(_currentUser.Id);
        var isAdmin = false;
        var userDTO = _userService.GetCurrentUser();
        foreach (var roleDTO in userDTO.RoleDTO)
        {
            if (roleDTO.IsAdmin)
            {
                isAdmin = true;
                CheckList.ItemsSource = checkListHeaderDTOs;
                break;
            }
        }

        if (!isAdmin)
        {
            var result = checkListHeaderDTOs
                          .Where(w => w.UserId == userDTO.Id && 
                                      //w.CheckStatus != CheckStatus.Blocked && 
                                      w.CheckStatus != CheckStatus.Sent &&
                                      w.CheckStatus != CheckStatus.Closed    
                                 ).ToList();
            CheckList.ItemsSource = result;
        }

        IsLoading = false;
    }

}

public class BlockedConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var canEnableBlocked = false;
        foreach (var roleDTO in SystemHelper.SystemUserDTO.RoleDTO)
        {
            if (roleDTO.CanEnableBlocked)
            {
                canEnableBlocked = true;
                break;
            }
        }
        if (value is CheckStatus status && canEnableBlocked)
        {
            return status == CheckStatus.InProgress;
        }
        return false;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
public class CloseConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var canEnableBlocked = false;
        foreach (var roleDTO in SystemHelper.SystemUserDTO.RoleDTO)
        {
            if (roleDTO.CanEnableBlocked)
            {
                canEnableBlocked = true;
                break;
            }
        }
        if (value is CheckStatus status && canEnableBlocked)
        {
            return true;
        }
        return false;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
public class UnBlockedConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var canEnableBlocked = false;
        foreach (var roleDTO in SystemHelper.SystemUserDTO.RoleDTO)
        {
            if (roleDTO.CanEnableBlocked)
            {
                canEnableBlocked = true;
                break;
            }
        }
        if (value is CheckStatus status)
        {
            if (status == CheckStatus.Blocked && canEnableBlocked)
            {
                return true;
            }
            return false;
        }
        return false;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
public class ContinueConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is CheckStatus status)
        {
            if (status == CheckStatus.InProgress || status == CheckStatus.Open)
            {
                return true;
            }
            return false;
        }
        return false;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
public class AcceptConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var canEnableBlocked = false;
        foreach (var roleDTO in SystemHelper.SystemUserDTO.RoleDTO)
        {
            if (roleDTO.CanEnableBlocked)
            {
                canEnableBlocked = true;
                break;
            }
        }
        if (value is CheckStatus status && canEnableBlocked)
        {
            if (status == CheckStatus.Sent)
            {
                return true;
            }
            return false;
        }
        return false;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}