using WorkFlowCheck.Common.DTO;
using WorkFlowCheck.MAUI.Services.Interfaces;
using System.Windows.Input;
using System.Globalization;
using System.Collections.ObjectModel;
using SkiaSharp;


namespace WorkFlowCheck.MAUI.Pages.CheckList;

public partial class CheckListWorkPage : ContentPage
{
    private readonly ICheckListService _checkListService;
    private readonly ISyncService _syncService;

    private string _checkPointCode;
    private int _checkListHeaderId;
    private UserDTO _userDTO;
    private bool _isLoading;


    public bool IsLoading
    {
        get => _isLoading;
        set
        {
            _isLoading = value;
            OnPropertyChanged(nameof(IsLoading));
        }
    }
    public ObservableCollection<CheckListRowDTO> CheckListRows { get; set; } = new ObservableCollection<CheckListRowDTO>();
    public ICommand CreatePhoto { get; set; }
    public ICommand SendCommand { get; set; }
    public ICommand SaveCommand { get; set; }

    public CheckListWorkPage(int checkListHeaderId, string checkPointCode)
    {
        InitializeComponent();
        _checkPointCode = checkPointCode;
        _checkListHeaderId = checkListHeaderId;
        _checkListService = MauiProgram.ServiceProvider.GetRequiredService<ICheckListService>();
        _syncService = MauiProgram.ServiceProvider.GetRequiredService<ISyncService>();
        _userDTO = MauiProgram.ServiceProvider.GetRequiredService<IUserService>().GetCurrentUser();

        SaveCommand = new Command(OnSave);
        SendCommand = new Command(OnSend);
    }

    private async void OnSend()
    {
        IsLoading = true;
        sendButton.IsEnabled = false;
        saveButton.IsEnabled = false;
        try
        {
            OnSave();



            await Task.Run(async () =>
            {
                var result = await _syncService.SyncCheckListHeader_Up(_checkListHeaderId, (percentage, infostring) =>
                {
                    // Direkt UI frissítés
                    MainThread.BeginInvokeOnMainThread(() =>
                    {
                        progressBar.Progress = percentage / 100;
                        progressLabel.Text = $"{infostring}: {percentage:0.00}%";
                    });
                });
                if (result.IsSuccess)
                {
                    if (Navigation.ModalStack.Count > 0)
                    {
                        await Shell.Current.Navigation.PopModalAsync();
                    }
                }
                else
                {
                    await Application.Current.MainPage.DisplayAlert("Hiba", result.Error, "OK");
                }
            });

            progressLabel.Text = "Szinkronizálás befejezve!";

        }
        catch (Exception ex)
        {
            await Application.Current.MainPage.DisplayAlert("Hiba", ex.Message, "OK");
            sendButton.IsEnabled = true;
            saveButton.IsEnabled = true;
        }
        finally
        {
            IsLoading = false;
        }

    }
    private async void OnSave()
    {
        IsLoading = true;
        try
        {
            await Task.Run(async () =>
            {
                foreach (var checkListRow in CheckListRows)
                {
                    if (checkListRow.AnswerYes == true)
                    {
                        checkListRow.Answer = "Igen";
                    }
                    if (checkListRow.AnswerNo == true)
                    {
                        checkListRow.Answer = "Nem";
                    }
                    await _checkListService.UpdateCheckListRow(checkListRow);
                }
                await LoadCheckPointCheckListRows();
            });
        }
        catch (Exception)
        {

        }
        finally
        {
            IsLoading = false;
        }
    }

    protected override async void OnAppearing()
    {
        base.OnAppearing();
        CreatePhoto = new Command<CheckListRowDTO>(OnTakePhoto);
        await LoadCheckPointCheckListRows();
        BindingContext = this;
    }
    private async void OnTakePhoto(CheckListRowDTO checkListRowDTO)
    {
        try
        {
            if (MediaPicker.IsCaptureSupported)
            {
                var photo = await MediaPicker.CapturePhotoAsync();
                if (photo != null)
                {
                    //using var stream = await photo.OpenReadAsync();
                    //using var ms = new MemoryStream();
                    //await stream.CopyToAsync(ms);
                    //byte[] photoBytes = ms.ToArray();

                    using var stream = await photo.OpenReadAsync();
                    using var originalBitmap = SKBitmap.Decode(stream);

                    int newWidth = 500;
                    int newHeight = (int)(originalBitmap.Height * ((double)newWidth / originalBitmap.Width));

                    using var surface = SKSurface.Create(new SKImageInfo(newWidth, newHeight));
                    using var canvas = surface.Canvas;

                    var sourceRect = new SKRect(0, 0, originalBitmap.Width, originalBitmap.Height);
                    var destRect = new SKRect(0, 0, newWidth, newHeight);
                    canvas.DrawBitmap(originalBitmap, sourceRect, destRect);

                    using var resizedImage = surface.Snapshot();
                    using var data = resizedImage.Encode(SKEncodedImageFormat.Jpeg, 100);

                    checkListRowDTO.Photo = data.ToArray();

                    await _checkListService.UpdateCheckListRow(checkListRowDTO);
                    await LoadCheckPointCheckListRows();
                }
            }
            else
            {
                Console.WriteLine("A fényképezés nem támogatott ezen az eszközön.");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Hiba történt a fényképezés közben: {ex.Message}");
        }
    }
    private async Task LoadCheckPointCheckListRows()
    {
        IsLoading = true;

        CheckListRows.Clear();
        var checkListRowDTOs = await _checkListService.GetCheckListRowsByCheckPointCode(_userDTO.Id, _checkListHeaderId, _checkPointCode);
        foreach (var item in checkListRowDTOs)
        {
            if (item.Answer == "Igen")
            {
                item.AnswerYes = true;
                item.AnswerNo = false;
            }
            else if (item.Answer == "Nem")
            {
                item.AnswerYes = false;
                item.AnswerNo = true;
            }
            CheckListRows.Add(item);
        }

        IsLoading = false;
    }

}
public class BindableRadioButton : RadioButton
{
    public static readonly BindableProperty BindableGroupNameProperty =
        BindableProperty.Create(nameof(BindableGroupName), typeof(string), typeof(BindableRadioButton), default(string), propertyChanged: OnGroupNameChanged);

    public string BindableGroupName
    {
        get => (string)GetValue(BindableGroupNameProperty);
        set => SetValue(BindableGroupNameProperty, value);
    }

    private static void OnGroupNameChanged(BindableObject bindable, object oldValue, object newValue)
    {
        if (bindable is BindableRadioButton radioButton && newValue is string newGroupName)
        {
            radioButton.GroupName = newGroupName;
        }
    }
}
public class ByteArrayToImageSourceConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is byte[] bytes && bytes.Length > 0)
        {
            return ImageSource.FromStream(() => new MemoryStream(bytes));
        }
        return null;
    }

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