using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Animation;
using CtrEditor.ObjetosSim;
using CtrEditor.FuncionesBase;

namespace CtrEditor.ObjetosSim.HydraulicComponents
{
    /// <summary>
    /// UserControl para la bomba hidráulica
    /// </summary>
    public partial class ucHydPump : UserControl, IDataContainer
    {
        public osBase? Datos { get; set; }
        public int zIndex_fromFrames { get; set; } = 0;
        
        private Storyboard? _rotationAnimation;
        private bool _isHighlighted = false;
        
        public ucHydPump()
        {
            InitializeComponent();
            this.Loaded += OnLoaded;
            this.Unloaded += OnUnloaded;
            DataContextChanged += OnDataContextChanged;
        }
        
        private void OnLoaded(object sender, RoutedEventArgs e)
        {
            Datos?.ucLoaded();
            UpdateVisualState();
        }
        
        private void OnUnloaded(object sender, RoutedEventArgs e)
        {
            Datos?.ucUnLoaded();
        }
        
        private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            if (DataContext is osHydPump pump)
            {
                Datos = pump;
                pump.PropertyChanged += OnPumpPropertyChanged;
                UpdateVisualState();
            }
        }
        
        private void OnPumpPropertyChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (e.PropertyName == nameof(osHydPump.IsRunning) ||
                e.PropertyName == nameof(osHydPump.SpeedRatio) ||
                e.PropertyName == nameof(osHydPump.PumpDirection) ||
                e.PropertyName == nameof(osHydPump.CurrentFlow) ||
                e.PropertyName == nameof(osHydPump.CurrentPressure))
            {
                UpdateVisualState();
            }
        }
        
        /// <summary>
        /// Actualiza el estado visual de la bomba
        /// </summary>
        private void UpdateVisualState()
        {
            if (Datos is not osHydPump pump) return;
            
            try
            {
                Dispatcher.BeginInvoke(() =>
                {
                    UpdateStatusLED(pump);
                    UpdateRotationAnimation(pump);
                    UpdateDirectionArrow(pump);
                    UpdateStatusInfo(pump);
                });
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Error updating pump visual state: {ex.Message}");
            }
        }
        
        /// <summary>
        /// Actualiza el LED de estado
        /// </summary>
        private void UpdateStatusLED(osHydPump pump)
        {
            if (pump.IsRunning && pump.SpeedRatio > 0)
            {
                StatusLED.Fill = new SolidColorBrush(Colors.LimeGreen);
            }
            else
            {
                StatusLED.Fill = new SolidColorBrush(Colors.Red);
            }
        }
        
        /// <summary>
        /// Actualiza la animación de rotación
        /// </summary>
        private void UpdateRotationAnimation(osHydPump pump)
        {
            _rotationAnimation?.Stop();
            
            if (pump.IsRunning && pump.SpeedRatio > 0)
            {
                // Crear animación de rotación
                var rotateTransform = new RotateTransform();
                PumpBackground.RenderTransform = rotateTransform;
                PumpBackground.RenderTransformOrigin = new Point(0.5, 0.5);
                
                var animation = new DoubleAnimation
                {
                    From = 0,
                    To = 360,
                    Duration = TimeSpan.FromSeconds(2.0 / pump.SpeedRatio), // Más rápido con mayor velocidad
                    RepeatBehavior = RepeatBehavior.Forever
                };
                
                _rotationAnimation = new Storyboard();
                Storyboard.SetTarget(animation, rotateTransform);
                Storyboard.SetTargetProperty(animation, new PropertyPath(RotateTransform.AngleProperty));
                _rotationAnimation.Children.Add(animation);
                _rotationAnimation.Begin();
            }
            else
            {
                PumpBackground.RenderTransform = null;
            }
        }
        
        /// <summary>
        /// Actualiza la flecha de dirección
        /// </summary>
        private void UpdateDirectionArrow(osHydPump pump)
        {
            if (pump.PumpDirection == -1)
            {
                // Cambiar el color de la flecha para indicar dirección inversa
                DirectionArrow.Fill = new SolidColorBrush(Colors.Orange);
            }
            else
            {
                DirectionArrow.Fill = new SolidColorBrush(Colors.DarkBlue);
            }
        }
        
        /// <summary>
        /// Actualiza la información de estado
        /// </summary>
        private void UpdateStatusInfo(osHydPump pump)
        {
            // La información de estado se mostrará a través de la etiqueta principal
            // El StatusLED ya está configurado para mostrar el estado IsRunning
        }
        
        #region IDataContainer Implementation
        
        public void Highlight(bool state)
        {
            _isHighlighted = state;
            
            if (state)
            {
                PumpBackground.Stroke = new SolidColorBrush(Colors.Yellow);
                PumpBackground.StrokeThickness = 3;
            }
            else
            {
                PumpBackground.Stroke = new SolidColorBrush(Colors.DarkSlateGray);
                PumpBackground.StrokeThickness = 2;
            }
        }
        
        #endregion
        
        protected override void OnMouseEnter(System.Windows.Input.MouseEventArgs e)
        {
            base.OnMouseEnter(e);
            // No hay elementos adicionales para mostrar en la implementación actual
        }
        
        protected override void OnMouseLeave(System.Windows.Input.MouseEventArgs e)
        {
            base.OnMouseLeave(e);
            // No hay elementos adicionales para ocultar en la implementación actual
        }
        
        public ZIndexEnum ZIndex_Base()
        {
            return ZIndexEnum.Estaticos;
        }
        
        ~ucHydPump()
        {
            _rotationAnimation?.Stop();
        }
    }
}
