/* eslint-disable react/prop-types */
import React, { useState, useRef, useEffect } from "react";
// interface KnobProps {
//   value?: number;
//   onChange?: (value: number) => void;
//   min?: number;
//   max?: number;
//   size?: 'sm' | 'md' | 'lg';
// }

export function Knob({ value = 0, onChange, min = 0, max = 100, size = "md" }) {
  //   const [localValue, setLocalValue] = useState(value);
  const isDragging = useRef(false);
  const startX = useRef(0);
  const startY = useRef(0);
  const startValue = useRef(0);

  const sizeClasses = {
    sm: "w-16 h-16",
    md: "w-24 h-24",
    lg: "w-32 h-32",
  };

  const dotSize = {
    sm: "w-2 h-2",
    md: "w-2.5 h-2.5",
    lg: "w-3 h-3",
  };

  const [rotation, setRotation] = useState(
    ((value - min) / (max - min)) * 270 - 135
  );

  const handleMouseDown = (e) => {
    isDragging.current = true;
    startX.current = e.clientX;
    startY.current = e.clientY;
    startValue.current = value;
    e.preventDefault();
  };

  useEffect(() => {
    const handleMouseMove = (e) => {
      if (!isDragging.current) return;

      const deltaX = e.clientX - startX.current;
      const deltaY = startY.current - e.clientY;
      const combinedDelta = deltaX + deltaY;
      const sensitivity = 0.01;
      const newValue = Math.max(
        min,
        Math.min(max, startValue.current + combinedDelta * sensitivity)
      );

      setRotation(((newValue - min) / (max - min)) * 270 - 135);
      onChange?.(newValue);
    };

    const handleMouseUp = () => {
      isDragging.current = false;
    };

    document.addEventListener("mousemove", handleMouseMove);
    document.addEventListener("mouseup", handleMouseUp);

    return () => {
      document.removeEventListener("mousemove", handleMouseMove);
      document.removeEventListener("mouseup", handleMouseUp);
    };
  }, [min, max, onChange]);

  useEffect(() => {
    setRotation(((value - min) / (max - min)) * 270 - 135);
  }, [value, min, max]);

  return (
    <div
      className={`${sizeClasses[size]} rounded-full bg-[#1a1a1a] border-2 border-[#2a2a2a] relative cursor-pointer select-none shadow-[inset_0_2px_8px_rgba(0,0,0,0.5),inset_0_-2px_6px_rgba(255,255,255,0.03),0_4px_12px_rgba(0,0,0,0.4)] overflow-hidden`}
      onMouseDown={handleMouseDown}
    >
      {/* Diffused top highlight */}
      <div className="absolute -top-1/4 left-0 right-0 h-3/4 bg-gradient-to-b from-white/[0.08] via-white/[0.02] to-transparent rounded-full pointer-events-none blur-sm" />

      <div
        className="absolute inset-0 flex items-start justify-center pt-2"
        style={{ transform: `rotate(${rotation}deg)` }}
      >
        <div
          className={`${dotSize[size]} rounded-full bg-primary shadow-primary/90 shadow-[0_0_12px]`}
        />
      </div>
    </div>
  );
}
