using UnityEngine;
using UnityEngine.UIElements;

namespace UVC.Twin.MonitoringUI
{
    public class BarChartElement : VisualElement
    {
        private readonly Label _label;
        private readonly VisualElement _track;
        private readonly VisualElement _primaryFill;
        private readonly VisualElement _secondaryFill;
        private readonly Label _primaryValueLabel;
        private readonly Label _secondaryValueLabel;

        public BarChartElement()
        {
            AddToClassList(CssClasses.BarChartRow);

            _label = new Label();
            _label.AddToClassList(CssClasses.BarChartLabel);
            Add(_label);

            var trackContainer = new VisualElement();
            trackContainer.AddToClassList(CssClasses.BarChartTrackContainer);

            _track = new VisualElement();
            _track.AddToClassList(CssClasses.BarChartTrack);

            _primaryFill = new VisualElement();
            _primaryFill.AddToClassList(CssClasses.BarChartFillPrimary);
            _track.Add(_primaryFill);

            _secondaryFill = new VisualElement();
            _secondaryFill.AddToClassList(CssClasses.BarChartFillSecondary);
            _track.Add(_secondaryFill);

            trackContainer.Add(_track);

            var valuesRow = new VisualElement();
            valuesRow.style.flexDirection = FlexDirection.Row;
            valuesRow.style.justifyContent = Justify.FlexEnd;

            _primaryValueLabel = new Label();
            _primaryValueLabel.AddToClassList(CssClasses.BarChartValuePrimary);

            _secondaryValueLabel = new Label();
            _secondaryValueLabel.AddToClassList(CssClasses.BarChartValueSecondary);

            valuesRow.Add(_primaryValueLabel);
            valuesRow.Add(_secondaryValueLabel);
            trackContainer.Add(valuesRow);

            Add(trackContainer);
        }

        public void SetData(BarChartItemData data)
        {
            _label.text = data.Label;

            float primaryPct = data.MaxValue > 0 ? (data.PrimaryValue / data.MaxValue) * 100f : 0;
            float secondaryPct = data.MaxValue > 0 ? (data.SecondaryValue / data.MaxValue) * 100f : 0;

            _primaryFill.style.width = new Length(primaryPct, LengthUnit.Percent);
            _secondaryFill.style.width = new Length(secondaryPct, LengthUnit.Percent);

            _primaryValueLabel.text = data.PrimaryValue.ToString("F0");
            _secondaryValueLabel.text = data.SecondaryValue.ToString("F0");
        }
    }
}
