using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;
using Portfolio.Domain.Features.TemperatureRange;

namespace Portfolio.WebUI.Server.Components.Component.Crochet_Components
{
    public partial class TemperatureRangeEditor : ComponentBase
    {
        [Parameter] public List<TemperatureRange> TempRanges { get; set; }

        [Parameter] public EventCallback<List<TemperatureRange>> OnRangesChanged { get; set; }

        [Inject] private IJSRuntime JS { get; set; }

        private double windowWidth = 1000;
        private int? draggingIndex = null;

        protected override async Task OnAfterRenderAsync(bool firstRender)
        {
            if (firstRender)
            {
                windowWidth = await JS.InvokeAsync<double>("eval", "window.innerWidth");
                StateHasChanged();
            }
        }

        private void OnMouseDown(int index, MouseEventArgs e)
        {
            draggingIndex = index;
        }

        private async void OnMouseUp()
        {
            if (draggingIndex != null)
            {
                draggingIndex = null;
                await OnRangesChanged.InvokeAsync(TempRanges);
            }
        }

        private void OnMouseMove(MouseEventArgs e)
        {
            if (draggingIndex is not int index || index <= 0 || index >= TempRanges.Count)
                return;

            var percent = (e.ClientX / windowWidth) * 100;
            percent = Math.Clamp(percent, 0, 100);

            var min = TempRanges[index - 1].Min;
            var max = TempRanges[index].Max;

            if (percent <= min + 1 || percent >= max - 1)
                return;

            TempRanges[index - 1].Max = percent;
            TempRanges[index].Min = percent;
        }

        private void HandleColorChange(ChangeEventArgs e, int index)
        {
            if (index < 0 || index >= TempRanges.Count)
            {
                Console.WriteLine($"Color change requested for out-of-bounds index: {index}");
                return;
            }

            var color = e?.Value?.ToString() ?? "#000000";
            OnColorChanged(index, color);
        }

        private async void OnColorChanged(int index, string newColor)
        {
            //Console.WriteLine($"Color change at index {index} to {newColor}");

            if (index >= 0 && index < TempRanges.Count)
            {
                TempRanges[index].Color = newColor;
                Console.WriteLine($"Updated color: {TempRanges[index].Color}");
                await OnRangesChanged.InvokeAsync(TempRanges);
            }
            else
            {
                Console.WriteLine($"Invalid index: {index} (Count: {TempRanges.Count})");
            }
        }
    }
}
