"use client";

import { useCallback, useEffect, useRef, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { useLanguage } from "@/lib/language-context";

interface Props {
  min: number;
  max: number;
  currency: string;
  labelMin: string;
  labelMax: string;
}

export default function PriceRangeSlider({
  min,
  max,
  currency,
  labelMin,
  labelMax,
}: Props) {
  const router = useRouter();
  const searchParams = useSearchParams();
  const { isRtl } = useLanguage();

  const step = max - min > 500 ? 10 : 1;
  const paramMin = searchParams.get("price_min");
  const paramMax = searchParams.get("price_max");

  const getValidRange = useCallback(() => {
    let loVal = paramMin !== null ? Number(paramMin) : min;
    let hiVal = paramMax !== null ? Number(paramMax) : max;
    if (loVal > hiVal - step) loVal = Math.max(min, hiVal - step);
    if (hiVal < loVal + step) hiVal = Math.min(max, loVal + step);
    return [loVal, hiVal] as const;
  }, [paramMin, paramMax, min, max, step]);

  const [lo, setLo] = useState(min);
  const [hi, setHi] = useState(max);

  useEffect(() => {
    const [loVal, hiVal] = getValidRange();
    setLo(loVal);
    setHi(hiVal);
  }, [getValidRange]);

  const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  const navigate = useCallback(
    (nextLo: number, nextHi: number) => {
      if (timerRef.current) clearTimeout(timerRef.current);
      timerRef.current = setTimeout(() => {
        const params = new URLSearchParams(searchParams.toString());
        params.delete("page");

        if (nextLo > min) {
          params.set("price_min", String(nextLo));
        } else {
          params.delete("price_min");
        }
        if (nextHi < max) {
          params.set("price_max", String(nextHi));
        } else {
          params.delete("price_max");
        }

        router.push(`/products?${params.toString()}`);
      }, 400);
    },
    [searchParams, min, max, router],
  );

  const handleLo = (e: React.ChangeEvent<HTMLInputElement>) => {
    const v = Math.min(Number(e.target.value), hi - step);
    setLo(v);
    navigate(v, hi);
  };

  const handleHi = (e: React.ChangeEvent<HTMLInputElement>) => {
    const v = Math.max(Number(e.target.value), lo + step);
    setHi(v);
    navigate(lo, v);
  };

  const handleMinBlur = () => {
    const clamped = Math.max(min, Math.min(hi - step, lo));
    if (clamped !== lo) {
      setLo(clamped);
      navigate(clamped, hi);
    }
  };

  const handleMaxBlur = () => {
    const clamped = Math.min(max, Math.max(lo + step, hi));
    if (clamped !== hi) {
      setHi(clamped);
      navigate(lo, clamped);
    }
  };

  const pctLo = ((lo - min) / (max - min)) * 100;
  const pctHi = ((hi - min) / (max - min)) * 100;

  if (min >= max) return null;

  return (
    <div className="space-y-4">
      {/* Input fields: label shows "Min (EGP)" so value is clearly just the number */}
      <div className="grid grid-cols-2 gap-3">
        <div>
          <label className="text-xs font-medium text-gray-500 mb-1.5 block">
            {labelMin} ({currency})
          </label>
          <input
            type="number"
            min={min}
            max={hi - step}
            step={step}
            value={lo}
            onChange={(e) => {
              const v = Math.min(Number(e.target.value), hi - step);
              setLo(v);
              navigate(v, hi);
            }}
            onBlur={handleMinBlur}
            className="w-full px-3 py-2.5 text-sm border-2 border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-colors bg-white"
          />
        </div>
        <div>
          <label className="text-xs font-medium text-gray-500 mb-1.5 block">
            {labelMax} ({currency})
          </label>
          <input
            type="number"
            min={lo + step}
            max={max}
            step={step}
            value={hi}
            onChange={(e) => {
              const v = Math.max(Number(e.target.value), lo + step);
              setHi(v);
              navigate(lo, v);
            }}
            onBlur={handleMaxBlur}
            className="w-full px-3 py-2.5 text-sm border-2 border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-colors bg-white"
          />
        </div>
      </div>
      <p className="text-xs text-gray-500 -mt-2">
        Use the slider or fields above. Min cannot exceed max.
      </p>

      {/* Dual-range track: dir=rtl so thumbs and track mirror correctly in RTL */}
      <div
        className="relative h-6 flex items-center"
        dir={isRtl ? "rtl" : "ltr"}
      >
        {/* Background track */}
        <div className="absolute inset-x-0 h-1.5 rounded-full bg-gray-200" />

        {/* Active range highlight — swap left/right in RTL so fill sits between thumbs */}
        <div
          className="absolute h-1.5 rounded-full"
          style={{
            ...(isRtl
              ? {
                  left: `${100 - pctHi}%`,
                  right: `${pctLo}%`,
                }
              : {
                  left: `${pctLo}%`,
                  right: `${100 - pctHi}%`,
                }),
            backgroundColor: "var(--color-primary, #10b981)",
          }}
        />

        {/* Min thumb */}
        <input
          type="range"
          min={min}
          max={max}
          step={step}
          value={lo}
          onChange={handleLo}
          className="price-range-thumb absolute inset-x-0"
          style={{ zIndex: lo > max - step ? 5 : 3 }}
        />

        {/* Max thumb */}
        <input
          type="range"
          min={min}
          max={max}
          step={step}
          value={hi}
          onChange={handleHi}
          className="price-range-thumb absolute inset-x-0"
          style={{ zIndex: 4 }}
        />
      </div>

      {/* Inline styles for the range thumbs */}
      <style>{`
        .price-range-thumb {
          -webkit-appearance: none;
          appearance: none;
          width: 100%;
          height: 24px;
          background: transparent;
          pointer-events: none;
          margin: 0;
          padding: 0;
        }
        .price-range-thumb::-webkit-slider-thumb {
          -webkit-appearance: none;
          appearance: none;
          height: 18px;
          width: 18px;
          border-radius: 9999px;
          background: white;
          border: 2px solid var(--color-primary, #10b981);
          box-shadow: 0 1px 3px rgba(0,0,0,0.15);
          cursor: pointer;
          pointer-events: all;
          transition: transform 0.15s ease, box-shadow 0.15s ease;
        }
        .price-range-thumb::-webkit-slider-thumb:hover {
          transform: scale(1.15);
          box-shadow: 0 2px 6px rgba(0,0,0,0.2);
        }
        .price-range-thumb::-moz-range-thumb {
          height: 18px;
          width: 18px;
          border-radius: 9999px;
          background: white;
          border: 2px solid var(--color-primary, #10b981);
          box-shadow: 0 1px 3px rgba(0,0,0,0.15);
          cursor: pointer;
          pointer-events: all;
        }
        .price-range-thumb::-moz-range-thumb:hover {
          transform: scale(1.15);
          box-shadow: 0 2px 6px rgba(0,0,0,0.2);
        }
      `}</style>
    </div>
  );
}
