using LSFE.MobApp.ViewModels.Coverage;

namespace LSFE.MobApp.Pages.CoveragePlan
{
    public partial class DoctorSignaturePage : ContentPage
    {
        private readonly DoctorSignatureVM _viewModel;

        public DoctorSignaturePage(DoctorSignatureVM viewModel)
        {
            InitializeComponent();
            _viewModel = viewModel;
            BindingContext = _viewModel;

            // Register the clear action with the ViewModel
            _viewModel.SetClearSignaturePadAction(() =>
            {
                SignaturePad.Clear();
                SignatureGuide.IsVisible = true;
                _viewModel.IsSignaturePadEmpty = true;
            });

            // Register the get signature bytes action
            _viewModel.SetGetSignatureBytesAction(async () =>
            {
                return await SignaturePad.GetSignatureImageAsync();
            });

            // Wire up signature pad commands
            WireUpSignaturePadCommands();

            // Wire up signature pad events for visual feedback
            WireUpSignaturePadEvents();
        }

        private void WireUpSignaturePadEvents()
        {
            // Hide guide text when user starts drawing
            SignaturePad.StartInteraction += (s, e) =>
            {
                SignatureGuide.IsVisible = false;
            };

            // Update empty state when drawing ends
            SignaturePad.EndInteraction += (s, e) =>
            {
                _viewModel.IsSignaturePadEmpty = SignaturePad.IsEmpty();
            };
        }
        private void WireUpSignaturePadCommands()
        {
            // Store reference to original command
            var originalClearAction = _viewModel.ClearSignature;

            // Replace with new command that calls both
            _viewModel.ClearSignatureCommand = new Command(() =>
            {
                SignaturePad.Clear();
                originalClearAction(); // Call the original ViewModel method
                SignatureGuide.IsVisible = true;
            });

            // Connect Preview command
            _viewModel.PreviewSignatureCommand = new Command(async () =>
            {
                if (SignaturePad.IsEmpty())
                {
                    await DisplayAlert("Empty Signature", "Please draw a signature first", "OK");
                    return;
                }

                try
                {
                    var signatureBytes = await SignaturePad.GetSignatureImageAsync();
                    if (signatureBytes != null && signatureBytes.Length > 0)
                    {
                        _viewModel.SetSignatureFromPad(signatureBytes);
                        await DisplayAlert("✅ Signature Saved",
                            "Signature captured successfully! Review it below and click 'Confirm & Save' when ready.",
                            "OK");
                    }
                    else
                    {
                        await DisplayAlert("Error", "Failed to capture signature. Please try again.", "OK");
                    }
                }
                catch (Exception ex)
                {
                    await DisplayAlert("Error", $"Failed to capture signature: {ex.Message}", "OK");
                }
            });
        }
        /*  private void WireUpSignaturePadCommands()
          {
              // The Clear command will now work through the ViewModel
              // No need to override it here anymore

              // Connect Preview command to capture and preview signature
              var originalPreviewCommand = _viewModel.PreviewSignatureCommand as Command;
              _viewModel.PreviewSignatureCommand = new Command(async () =>
              {
                  if (SignaturePad.IsEmpty())
                  {
                      await DisplayAlert("Empty Signature", "Please draw a signature first", "OK");
                      return;
                  }

                  try
                  {
                      var signatureBytes = await SignaturePad.GetSignatureImageAsync();
                      if (signatureBytes != null && signatureBytes.Length > 0)
                      {
                          _viewModel.SetSignatureFromPad(signatureBytes);
                          await DisplayAlert("✅ Signature Saved", "Signature captured successfully! Review it below and click 'Confirm & Save' when ready.", "OK");
                      }
                      else
                      {
                          await DisplayAlert("Error", "Failed to capture signature. Please try again.", "OK");
                      }
                  }
                  catch (Exception ex)
                  {
                      await DisplayAlert("Error", $"Failed to capture signature: {ex.Message}", "OK");
                  }
              });
          }*/
        protected override void OnAppearing()
        {
            base.OnAppearing();

            // Request camera and storage permissions on page load
            RequestPermissions();
        }

        private async void RequestPermissions()
        {
            try
            {
                // Request camera permission
                var cameraStatus = await Permissions.CheckStatusAsync<Permissions.Camera>();
                if (cameraStatus != PermissionStatus.Granted)
                {
                    cameraStatus = await Permissions.RequestAsync<Permissions.Camera>();
                }

                // Request photos permission
                var photosStatus = await Permissions.CheckStatusAsync<Permissions.Photos>();
                if (photosStatus != PermissionStatus.Granted)
                {
                    photosStatus = await Permissions.RequestAsync<Permissions.Photos>();
                }

                // Request media permission (for Android 13+)
                var mediaStatus = await Permissions.CheckStatusAsync<Permissions.Media>();
                if (mediaStatus != PermissionStatus.Granted)
                {
                    mediaStatus = await Permissions.RequestAsync<Permissions.Media>();
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"Permission request failed: {ex.Message}");
            }
        }
    }
}