using Bimix.UI.Shared.Interfaces;
using ZXing.Net.Maui;
using ZXing.Net.Maui.Controls;

namespace Bimix.UI.Mobile.Services;

public class ScannerService : IScannerService
{
    public bool IsAvailable => true;

    public async Task<string?> ScanBarcodeAsync()
    {
        try
        {
            if (!IsAvailable)
                return null;
            
            var hasPermission = await RequestCameraPermissionsAsync();
            if (!hasPermission)
                return null;
            
            var tcs = new TaskCompletionSource<string?>();

            await MainThread.InvokeOnMainThreadAsync(async () =>
            {
                var scanner = new CameraBarcodeReaderView
                {
                    Options = new BarcodeReaderOptions
                    {
                        Formats = BarcodeFormats.OneDimensional | BarcodeFormats.TwoDimensional,
                        AutoRotate = true,
                        Multiple = false
                    },
                    HorizontalOptions = LayoutOptions.FillAndExpand,
                    VerticalOptions = LayoutOptions.FillAndExpand,
                    BackgroundColor = Colors.Black
                };

                scanner.BarcodesDetected += async (sender, e) =>
                {
                    if (e.Results?.Any() == true)
                    {
                        var barcode = e.Results.First();
                        
                        // Wykonaj operacje UI na głównym wątku
                        await MainThread.InvokeOnMainThreadAsync(async () =>
                        {
                            try
                            {
                                await Microsoft.Maui.Controls.Application.Current?.MainPage?.Navigation.PopModalAsync()!;
                                tcs.TrySetResult(barcode.Value);
                            }
                            catch (Exception ex)
                            {
                                System.Diagnostics.Debug.WriteLine($"Error closing modal: {ex.Message}");
                                tcs.TrySetException(ex);
                            }
                        });
                    }
                };

                var cancelButton = new Button
                {
                    Text = "Anuluj",
                    BackgroundColor = Colors.Red,
                    TextColor = Colors.White,
                    Margin = new Thickness(20),
                    HorizontalOptions = LayoutOptions.Center
                };

                cancelButton.Clicked += async (sender, e) =>
                {
                    try
                    {
                        await Microsoft.Maui.Controls.Application.Current?.MainPage?.Navigation.PopModalAsync()!;
                        tcs.TrySetResult(null);
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine($"Error closing modal: {ex.Message}");
                        tcs.TrySetException(ex);
                    }
                };

                var stackLayout = new StackLayout
                {
                    Children = 
                    {
                        new Label 
                        { 
                            Text = "Skieruj kamerę na kod kreskowy",
                            HorizontalOptions = LayoutOptions.Center,
                            VerticalOptions = LayoutOptions.Start,
                            Margin = new Thickness(20),
                            FontSize = 18,
                            TextColor = Colors.White
                        },
                        scanner,
                        cancelButton
                    },
                    BackgroundColor = Colors.Black,
                    Spacing = 0
                };

                var scannerPage = new ContentPage
                {
                    Title = "Skanuj kod",
                    Content = stackLayout,
                    BackgroundColor = Colors.Black
                };

                await Microsoft.Maui.Controls.Application.Current?.MainPage?.Navigation.PushModalAsync(scannerPage)!;
            });
            
            var result = await tcs.Task;
            System.Diagnostics.Debug.WriteLine($"Scanner returned: {result}");
            return result;

        }
        catch (Exception e)
        {
            System.Diagnostics.Debug.WriteLine($"Scanner error: {e.Message}");
            return null;
        }
    }
    
    public async Task<bool> RequestCameraPermissionsAsync()
    {
        try
        {
            var status = await Permissions.RequestAsync<Permissions.Camera>();
            return status == PermissionStatus.Granted;
        }
        catch (Exception e)
        {
            System.Diagnostics.Debug.WriteLine($"Permission error: {e.Message}");
            return false;
        }
    }
}