using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;

namespace WindowsFormsApp1
{
    public class RangeSlider : Control
    {
        public int Minimum { get; set; } = 0;
        public int Maximum { get; set; } = 100;
        public int LeftValue { get; set; } = 20;
        public int RightValue { get; set; } = 80;

        private bool draggingLeft = false;
        private bool draggingRight = false;
        private int thumbWidth = 10;

        public RangeSlider()
        {
            this.DoubleBuffered = true;
            this.Height = 30;
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            // 1. Draw the Track
            Rectangle trackRect = new Rectangle(thumbWidth / 2, Height / 2 - 2, Width - thumbWidth, 4);
            TrackBarRenderer.DrawHorizontalTrack(e.Graphics, trackRect);

            // 2. Calculate Thumb Positions
            int leftX = ValueToX(LeftValue);
            int rightX = ValueToX(RightValue);

            // 3. Draw Thumbs
            Rectangle leftThumb = new Rectangle(leftX - thumbWidth / 2, Height / 2 - 8, thumbWidth, 16);
            Rectangle rightThumb = new Rectangle(rightX - thumbWidth / 2, Height / 2 - 8, thumbWidth, 16);

            TrackBarRenderer.DrawHorizontalThumb(e.Graphics, leftThumb, draggingLeft ? TrackBarThumbState.Pressed : TrackBarThumbState.Normal);
            TrackBarRenderer.DrawHorizontalThumb(e.Graphics, rightThumb, draggingRight ? TrackBarThumbState.Pressed : TrackBarThumbState.Normal);
        }

        protected override void OnMouseDown(MouseEventArgs e)
        {
            int leftX = ValueToX(LeftValue);
            int rightX = ValueToX(RightValue);

            if (Math.Abs(e.X - leftX) < thumbWidth) draggingLeft = true;
            else if (Math.Abs(e.X - rightX) < thumbWidth) draggingRight = true;
        }

        protected override void OnMouseMove(MouseEventArgs e)
        {
            if (draggingLeft)
            {
                LeftValue = Math.Min(XToValue(e.X), RightValue - 1);
                Invalidate();
            }
            else if (draggingRight)
            {
                RightValue = Math.Max(XToValue(e.X), LeftValue + 1);
                Invalidate();
            }
        }

        protected override void OnMouseUp(MouseEventArgs e)
        {
            draggingLeft = draggingRight = false;
        }

        private int ValueToX(int val) => (int)((float)(val - Minimum) / (Maximum - Minimum) * (Width - thumbWidth)) + thumbWidth / 2;
        private int XToValue(int x) => (int)((float)(x - thumbWidth / 2) / (Width - thumbWidth) * (Maximum - Minimum)) + Minimum;
    }
}
