"use client";

import { useTranslations } from "next-intl";
import { useState, useEffect } from "react";

interface PriceSliderProps {
  min: number;
  max: number;
  value: [number, number];
  onChange?: (value: [number, number]) => void;
  onCommit?: (value: [number, number]) => void;
}

export default function PriceSlider({
  min,
  max,
  value,
  onChange,
  onCommit,
}: PriceSliderProps) {
  const t = useTranslations();
  if (
    min === undefined ||
    max === undefined ||
    min >= max ||
    min < 0 ||
    max <= 0 ||
    (min === 0 && max === 0)
  ) {
    return (
      <div className="w-full">
        <div className="text-sm text-neutrals500 dark:text-neutrals400 py-4 text-center">
          {t("invalid_price_range")}
        </div>
      </div>
    );
  }

  const [isActive, setIsActive] = useState(false);
  const [currentRange, setCurrentRange] = useState<[number, number]>(value);

  useEffect(() => {
    setCurrentRange(value);
  }, [value[0], value[1]]);

  const denominator = Math.max(1, max - min);
  const percentage = Math.min(
    Math.max(((currentRange[1] - min) / denominator) * 100, 0),
    100
  );
  const step = 1000;
  const formatSAR = (val: number) => `SAR ${val.toLocaleString("en-IN")}`;

  // Calculate tooltip position to prevent overflow
  const getTooltipPosition = () => {
    const clampedPercentage = Math.min(Math.max(percentage, 5), 95);
    return `${clampedPercentage}%`;
  };

  return (
    <div className="w-full max-w-full">
      {/* Labels */}
      <div className="flex justify-between text-xs font-semibold text-primary500 mb-2 dark:text-primary400">
        <span className="text-xs truncate max-w-[40%]">{formatSAR(min)}</span>
        <span className="text-xs truncate max-w-[40%] text-right">
          {formatSAR(max)}
        </span>
      </div>
      <div className="relative w-full h-6 max-w-full">
        {isActive && (
          <div
            className="absolute -top-11 bg-white text-xs font-semibold text-primary500 px-2 py-1.5 rounded shadow z-20 transition-all dark:text-primary400 max-w-[120px]"
            style={
              {
                left: getTooltipPosition(),
                transform: "translateX(-50%)",
              } as React.CSSProperties
            }
          >
            <span className="block truncate">{formatSAR(currentRange[1])}</span>
            <div className="absolute bottom-[-6px] left-1/2 -translate-x-1/2 w-3 h-3 bg-white rotate-45 shadow-sm" />
          </div>
        )}
        <div className="absolute top-1/2 left-0 right-0 h-1.5 rounded-full bg-neutrals200 -translate-y-1/2 dark:bg-cardfooter" />
        <div
          className="absolute top-1/2 h-1.5 rounded-full bg-primary500 -translate-y-1/2 dark:bg-primary400 max-w-full"
          style={{ width: `${Math.min(percentage, 100)}%` }}
        />
        <div
          className="absolute top-1/2 w-4 h-4 bg-primary500 border-2 dark:bg-primary400 border-neutrals200 rounded-full -translate-x-1/2 -translate-y-1/2 z-10 pointer-events-none"
          style={
            { left: `${Math.min(percentage, 100)}%` } as React.CSSProperties
          }
        />
        <input
          type="range"
          min={min}
          max={max}
          step={step}
          value={currentRange[1]}
          onChange={(e) => {
            // const newMax = Number(e.target.value);
            // // Clamp to max if the remainder is less than one step
            // const remainder = max - newMax;
            // const snapped = remainder > 0 && remainder < step ? max : newMax;
            // const next: [number, number] = [currentRange[0], snapped];
            // setCurrentRange(next);
            // // optional: notify live without fetching
            // onChange && onChange(next);

            setCurrentRange([value[0], Number(e.target.value)]);
          }}
          onMouseDown={() => setIsActive(true)}
          onMouseUp={() => {
            setIsActive(false);
            // Snap to max if within half a step when releasing
            const snappedMax =
              currentRange[1] >= max - step / 2 ? max : currentRange[1];
            const next: [number, number] = [currentRange[0], snappedMax];
            setCurrentRange(next);
            onCommit && onCommit(next);
          }}
          onTouchStart={() => setIsActive(true)}
          onTouchEnd={() => {
            setIsActive(false);
            const snappedMax =
              currentRange[1] >= max - step / 2 ? max : currentRange[1];
            const next: [number, number] = [currentRange[0], snappedMax];
            setCurrentRange(next);
            onCommit && onCommit(next);
          }}
          className="absolute top-1/2 left-0 w-full h-2 opacity-0 cursor-pointer z-20"
          style={{ transform: "translateY(-50%)" }}
        />
      </div>
    </div>
  );
}
