import React, { useState, useEffect, useMemo } from "react";
import { View, Text, Image } from "@tarojs/components";
import { Range } from "@nutui/nutui-react-taro";
import styles from "./index.module.scss";
import TitleComponent from "../Title";
import img from "../../config/images";

interface RangeProps {
  min?: number;
  max?: number;
  step?: number;
  value?: [number, number];
  onChange?: {
    (value: [number, number]): void
    (name: string, value: [number, number]): void
  };
  disabled?: boolean;
  className?: string;
  name?: string;
  showTitle?: boolean;
}

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

  useEffect(() => {
    value && setCurrentValue(value);
  }, [JSON.stringify(value || [])]);

  const handleChange = (val: [number, number]) => {
    setCurrentValue(val);
    // onChange?.(name, val);
  };

  const handleEndChange = (val: [number, number]) => {
    setCurrentValue(val);
    if (name) {
      onChange?.(name, val);
    } else {
      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 (Number(start) === Number(min) && Number(end) === Number(max)) {
      return "不限";
    }
    return `${start?.toFixed(1)} - ${end?.toFixed(1)}之间`;
  }, [JSON.stringify(currentValue || []), min, max]);

  return (
    <div className={`${styles.nutRange} ${className ? className : ""} `}>
      {showTitle && (
        <div className={styles.nutRangeHeader}>
          <TitleComponent
            title="NTRP水平区间"
            icon={<Image src={img.ICON_PLAY} />}
          />
          <p className={styles.nutRangeHeaderContent}>{rangContent}</p>
        </div>
      )}

      <div>
        <div className={`${styles.rangeWrapper} rangeContent`}>
          <span className={styles.rangeWrapperMin}>{min.toFixed(1)}</span>
          <Range
            range
            min={min}
            max={max}
            step={step}
            value={currentValue}
            onEnd={handleEndChange}
            onChange={handleChange}
            disabled={disabled}
            defaultValue={[min, max]}
            className={styles.rangeHandle}
            maxDescription={null}
            minDescription={null}
            currentDescription={null}
            marks={marks}
          />
          <span className={styles.rangeWrapperMax}>{max.toFixed(1)}</span>
        </div>
      </div>
    </div>
  );
};

export default NtrpRange;
