import React, { useState, useEffect, useMemo } from "react";
import { Range } from "@nutui/nutui-react-taro";
import "./index.scss";

interface RangeProps {
  min?: number;
  max?: number;
  step?: number;
  value?: [number, number];
  onChange?: (value: [number, number]) => void;
  disabled?: boolean;
}

const NtrpRange: React.FC<RangeProps> = ({
  min = 1.0,
  max = 5.0,
  step = 0.5,
  value = [min, max],
  onChange,
  disabled = false,
}) => {
  const [currentValue, setCurrentValue] = useState<[number, number]>(value);

  useEffect(() => {
    setCurrentValue(value);
  }, [value]);

  const handleChange = (val: [number, number]) => {
    console.log("Range value changed:", val);
    setCurrentValue(val);
    onChange?.(val);
  };

  const marks = useMemo(() => {
    let marksMap = {};
    for (let i = min + step; i < max; i += step) {
      marksMap[i] = "";
    }
    return marksMap;
  }, [min, max, step]);

  const rangContent = useMemo(() => {
    const [start, end] = currentValue || [];
    if (start === min && end === max) {
      return "不限";
    }
    return `${start.toFixed(1)} - ${end.toFixed(1)}之间`;
  }, [currentValue, min, max]);

  return (
    <div className="ntrp-range">
      <div className="ntrp-range__header">
        <div className="ntrp-range__header-left">
          <div className="ntrp-range__icon">icon</div>
          <h3 className="ntrp-range__title">NTRP水平区间</h3>
        </div>
        <p className="ntrp-range__content">{rangContent}</p>
      </div>

      <div>
        <div className="rangeWrapper">
          <span className="rangeWrapper__min">{min}</span>
          <Range
            range
            min={min}
            max={max}
            step={step}
            value={currentValue}
            onChange={handleChange}
            disabled={disabled}
            defaultValue={[min, max]}
            className="rangeHandle"
            maxDescription={null}
            minDescription={null}
            currentDescription={null}
            marks={marks}
            style={{ color: "gold" }}
          />
          <span className="rangeWrapper__max">{max}</span>
        </div>
      </div>

      {/* 调试信息 */}
      <div style={{ marginTop: "10px", fontSize: "12px", color: "#666" }}>
        当前值: {currentValue[0].toFixed(1)} - {currentValue[1].toFixed(1)}
      </div>
    </div>
  );
};

export default NtrpRange;
