using System.ComponentModel;
using Avalonia.Controls;
using VisionBuilder.UI.Avalonia.Services;
using VisionBuilder.UI.Common.ViewModel;

namespace VisionBuilder.UI.Avalonia.Views;

public partial class ImagePreviewDialog : Window
{
    private readonly ErrorPreviewVM _previewVm;

    public ImagePreviewDialog(ErrorPreviewVM errorPreviewVm)
    {
        _previewVm = errorPreviewVm;

        InitializeComponent();

        _previewVm.PropertyChanged += PreviewVm_PropertyChanged;

        // Initial state
        UpdateImage();
        BtnLearn.IsVisible = _previewVm.LearnButtonVisible;
        BtnPrev.IsEnabled = _previewVm.IsPreviousImageEnabled;
        BtnNext.IsEnabled = _previewVm.IsNextImageEnabled;
        LblImageName.Text = _previewVm.ImageName;

        // Wire button events (direct method calls like WinForms)
        BtnPrev.Click += (_, _) => _previewVm.PreviousImage();
        BtnNext.Click += (_, _) => _previewVm.NextImage();
        BtnSwitchView.Click += (_, _) => _previewVm.SwitchView();
        BtnLearn.Click += (_, _) => _previewVm.Learn();
        BtnClose.Click += (_, _) => Close();
    }

    private void PreviewVm_PropertyChanged(object? sender, PropertyChangedEventArgs e)
    {
        global::Avalonia.Threading.Dispatcher.UIThread.Post(() =>
        {
            switch (e.PropertyName)
            {
                case nameof(ErrorPreviewVM.ImageAnalysis):
                    UpdateImage();
                    break;
                case nameof(ErrorPreviewVM.LearnButtonVisible):
                    BtnLearn.IsVisible = _previewVm.LearnButtonVisible;
                    break;
                case nameof(ErrorPreviewVM.IsPreviousImageEnabled):
                    BtnPrev.IsEnabled = _previewVm.IsPreviousImageEnabled;
                    break;
                case nameof(ErrorPreviewVM.IsNextImageEnabled):
                    BtnNext.IsEnabled = _previewVm.IsNextImageEnabled;
                    break;
                case nameof(ErrorPreviewVM.ImageName):
                    LblImageName.Text = _previewVm.ImageName;
                    break;
                case nameof(ErrorPreviewVM.OriginalView):
                    BtnSwitchView.Content = _previewVm.OriginalView ? "SHOW ANALYSIS" : "SHOW ORIGINAL";
                    break;
            }
        });
    }

    private void UpdateImage()
    {
        if (_previewVm.ImageAnalysis != null && !_previewVm.ImageAnalysis.Empty())
        {
            PreviewImage.Source = ImageConverter.MatToAvaloniaBitmap(_previewVm.ImageAnalysis);
        }
        else
        {
            PreviewImage.Source = null;
        }
    }
}
