import * as React from "react";
import * as SliderPrimitive from "@radix-ui/react-slider";
import {
  Tooltip,
  TooltipProvider,
  TooltipContent,
  TooltipTrigger,
} from "../ui/tooltip";
import { cn } from "../../lib/utils";

interface SingleThumbSliderProps
  extends Omit<
    React.ComponentPropsWithoutRef<typeof SliderPrimitive.Root>,
    "value" | "defaultValue" | "onValueChange"
  > {
  /** If true, show a tooltip when hovering the thumb */
  tooltip?: boolean;
  /** Position of the tooltip relative to the thumb */
  tooltip_direction?: "top" | "bottom";
  /**
   * Controlled value for the slider (single thumb).
   * If this is set, the parent component is responsible for updating it in `onValueChange`.
   */
  value?: number;
  /** Uncontrolled default value for the slider (single thumb). Used if `value` is not provided. */
  defaultValue?: number;
  /** Handler called when the slider value changes. Receives the new numeric value. */
  onValueChange?: (newValue: number) => void;
}

const Slider = React.forwardRef<
  React.ElementRef<typeof SliderPrimitive.Root>,
  SingleThumbSliderProps
>((props, ref) => {
  const {
    className,
    tooltip = false,
    tooltip_direction = "top",
    value,
    defaultValue,
    onValueChange,
    ...restProps
  } = props;

  // If both value and defaultValue are undefined, fall back to 30
  const initialValue = value ?? defaultValue ?? 30;
  const [sliderValue, setSliderValue] = React.useState<number>(initialValue);

  React.useEffect(() => {
    // If `value` changes externally (controlled usage), sync local state
    if (typeof value === "number") {
      setSliderValue(value);
    }
  }, [value]);

  const handleValueChange = (newValues: number[]) => {
    // For a single-thumb slider, we'll only need the first value
    const newValue = newValues[0];
    setSliderValue(newValue);

    if (onValueChange) {
      onValueChange(newValue);
    }
  };

  // Optional class styling for the tooltip if direction is "bottom"
  const tooltipClass =
    tooltip_direction === "bottom" ? "bg-white text-black" : "";

  return (
    <TooltipProvider>
      <SliderPrimitive.Root
        ref={ref}
        className={cn(
          "relative flex w-80 touch-none select-none items-center",
          className
        )}
        // Pass an array here because Radix Slider always expects an array for `value`.
        value={[sliderValue]}
        onValueChange={handleValueChange}
        {...restProps}
      >
        <SliderPrimitive.Track className="relative h-2 w-full overflow-hidden bg-bg-quaternary">
          <SliderPrimitive.Range className="absolute h-full bg-fg-brand-primary" />
        </SliderPrimitive.Track>

        <SliderPrimitive.Thumb
          className={cn(
            "block h-6 w-6 rounded-full border-2 border-bg-brand-solid bg-white shadow transition-colors",
            "focus-visible:outline-none focus-visible:outline focus-visible:outline-2 focus-visible:outline-bg-brand-solid focus-visible:outline-offset-2",
            "disabled:pointer-events-none disabled:opacity-50"
          )}
        >
          {tooltip && (
            <Tooltip>
              <TooltipTrigger asChild>
                {/* This div ensures the thumb itself is the trigger area */}
                <div className="w-full h-full" />
              </TooltipTrigger>
              <TooltipContent
                sideOffset={12}
                side={tooltip_direction}
                align="center"
                className={cn("text-xs rounded", tooltipClass)}
              >
                {sliderValue}
              </TooltipContent>
            </Tooltip>
          )}
        </SliderPrimitive.Thumb>
      </SliderPrimitive.Root>
    </TooltipProvider>
  );
});

// const ComposedSlider = React.forwardRef<
//   React.ElementRef<typeof SliderPrimitive.Root>,
//   React.ComponentPropsWithoutRef<typeof SliderPrimitive.Root> & {
//     tooltip?: boolean;
//     tooltip_direction?: "top" | "bottom";
//     thumbCount?: 1 | 2;
//   }
// >(
//   (
//     {
//       className,
//       tooltip = false,
//       tooltip_direction = "top",
//       thumbCount = 2,
//       value,
//       defaultValue,
//       onValueChange,
//       ...props
//     },
//     ref
//   ) => {
//     const initialValues = value || defaultValue || [30, 70];
//     const [sliderValues, setSliderValues] = React.useState<number[]>(
//       initialValues.slice(0, thumbCount)
//     );

//     React.useEffect(() => {
//       if (thumbCount === 1 && sliderValues.length === 2) {
//         setSliderValues([sliderValues[0]]);
//       } else if (thumbCount === 2 && sliderValues.length === 1) {
//         setSliderValues([sliderValues[0], 70]);
//       }
//     }, [thumbCount]);

//     const formattedValues = sliderValues.map((v) => ${v.toFixed(0)}%);

//     const handleValueChange = (newValue: number[]) => {
//       setSliderValues(newValue);
//       if (onValueChange) {
//         onValueChange(newValue);
//       }
//     };

//     return (
//       <TooltipProvider>
//         <SliderPrimitive.Root
//           ref={ref}
//           className={cn(
//             "relative flex w-80 touch-none select-none items-center",
//             className
//           )}
//           value={sliderValues}
//           onValueChange={handleValueChange}
//           {...props}
//         >
//           <SliderPrimitive.Track className="relative h-2 w-full overflow-hidden bg-bg-quaternary">
//             <SliderPrimitive.Range className="absolute h-full bg-fg-brand-primary" />
//           </SliderPrimitive.Track>
//           {sliderValues.map((val, index) => {
//             const thumb = (
//               <SliderPrimitive.Thumb
//                 key={index}
//                 className={cn(
//                   "block h-6 w-6 rounded-full border-2 border-bg-brand-solid bg-white shadow transition-colors focus-visible:outline-none focus-visible:outline focus-visible:outline-2 focus-visible:outline-bg-brand-solid focus-visible:outline-offset-2 disabled:pointer-events-none disabled:opacity-50"
//                 )}
//               />
//             );

//             return tooltip ? (
//               <Tooltip key={index}>
//                 <TooltipTrigger asChild>{thumb}</TooltipTrigger>
//                 <TooltipContent side={tooltip_direction} align="center">
//                   {formattedValues[index]}
//                 </TooltipContent>
//               </Tooltip>
//             ) : (
//               thumb
//             );
//           })}
//         </SliderPrimitive.Root>
//       </TooltipProvider>
//     );
//   }
// );

Slider.displayName = "Slider";

export { Slider };
