import React, { useState, useEffect } from 'react';
// import clsx from 'clsx';
// import { View } from '@ray-js/ray';
import { DpBooleanAction, DpCommonAction } from '@ray-js/panel-sdk';
import { useSdmProps } from '@ray-js/panel-sdk';
import { devices } from '@/devices';
import styles from './index.module.less';
import { Image, View } from '@ray-js/components';
import iconClose from '../../../public/icon-close.png';
import iconLightWhite from '../../../public/icon-light-white.png';
import iconSun from '../../../public/icon-sun.png';
// import { usePageEvent } from '@ray-js/ray';
export interface Props {
  isShow: boolean;
  setModal: (boolean) => void;
}

export const LightPanel = React.memo<Props>(props => {
  const brightRange = [10, 1000];
  const cctRange = [0, 1000];

  const brightCode = 'bright_value';
  const temperatureCode = 'temp_value';
  const switchCode = 'light';

  let { isShow, setModal } = props;
  const brightVal = useSdmProps(dpState => {
    const val = dpState[brightCode];
    const percent = getValueInRange(val || 10, brightRange).percent;
    return percent;
  });

  const temperatureVal = useSdmProps(dpState => {
    const val = dpState[temperatureCode];
    const originX = getOrignPointX(val);
    return originX;
  });
  const switchVal = useSdmProps(dpState => dpState[switchCode]);

  const device = devices.fan;
  const actions = device.model.actions;
  const switchAction = actions[switchCode] as DpBooleanAction;
  const brightAction = actions[brightCode] as DpCommonAction<number>;
  const temperatureAction = actions[temperatureCode] as DpCommonAction<number>;

  const [point, setPoint] = useState({ pageX: temperatureVal, pageY: 250 });
  const [brightPercent, setBrightPercent] = useState(brightVal);

  useEffect(() => {
    if (brightVal !== brightPercent) {
      setBrightPercent(brightVal);
    }
  }, [brightVal]);

  // useEffect(() => {
  //   if (temperatureVal !== point.pageX) {
  //       setPoint({ pageX: temperatureVal, pageY: 250 })
  //   }
  // }, [temperatureVal])

  function getOrignPointX(val = temperatureVal) {
    const percent = getValueInRange(val || 10, cctRange).percent;
    const originX = 28 + 319 * (percent / 100);
    console.log(val, percent, originX);
    return originX;
  }
  //0-value是值 1-value是百分比 左边最小值是0，右边最大值range[1]，起始位置rang[0]
  function getValueInRange(value, range, type = 0) {
    const percent = type == 0 ? value / range[1] : value / 100;
    return {
      value: type == 0 ? value : (percent * range[1]).toFixed(),
      percent: type == 0 ? (percent * 100).toFixed() : value,
    };
  }

 

  function touchStart(e) {
    // e.origin.stopPropagation();
    // handlePoint(e);
  }

  function handleTouch(e) {
    // e.origin.stopPropagation();
    handlePoint(e, false);
  }

  function touchEnd(e) {
    console.log(e, 'touchEnd');
    handlePoint(e);
  }

  function handlePoint(e, isAction = true) {
    const { pageX, pageY } = e.changedTouches.length && e.changedTouches[0];
    let x = pageX;
    let y = pageY;
    const xRange = [28, 347];
    if (pageX < xRange[0]) {
      x = xRange[0];
    }
    if (pageX > xRange[1]) {
      x = xRange[1];
    }
    if (pageY < 197) {
      y = 197;
    }
    if (pageY > 320) {
      y = 320;
    }

    setPoint({ pageX: x, pageY: y });
    console.log(x, y, 'xxxxxxyyyyyyyy');
    const percent = (x - xRange[0]) / (xRange[1] - xRange[0]);
    const value = Number((cctRange[1] * percent).toFixed());
    // setColor(pointToRGB(x));
    if (isAction) {
      temperatureAction.set(value);
    }
  }

  // function pointToRGB(pageX) {
  //   const half = (347 - 28) / 2;
  //   const middle = 28 + half;
  //   const leftColor = { h: 40, s: 100, l: 68 };
  //   const rightColor = { h: 202, s: 96, l: 90 };
  //   let newL = leftColor.l;
  //   let color = leftColor;
  //   if (pageX < middle) {
  //     newL = 68 + ((pageX - 28) * 32) / 161;
  //     leftColor.l = newL;
  //     color = leftColor;
  //   } else {
  //     newL = 100 - ((pageX - middle) * 10) / 161;
  //     rightColor.l = newL;
  //     color = rightColor;
  //   }
  //   return HSLToRGB(color);
  // }

  // function HSLToRGB({ h, s, l }) {
  //   s /= 100;
  //   l /= 100;
  //   const k = n => (n + h / 30) % 12;
  //   const a = s * Math.min(l, 1 - l);
  //   const f = n => l - a * Math.max(-1, Math.min(k(n) - 3, Math.min(9 - k(n), 1)));
  //   const color = `rgb(${255 * f(0)},  ${255 * f(8)}, ${255 * f(4)})`;
  //   console.log(color);
  //   return color;
  // }

  const handleLightOn = () => {
    switchAction.toggle();
  };

  function progressStart(e) {
    console.log(e, 'progressStart');
    e.origin.stopPropagation();
    handleProgress(e);
  }

  function progressMove(e) {
    // console.log(e, 'progressMove');
    handleProgress(e, false);
  }

  function progressEnd(e) {
    console.log(e, 'progressEnd');
    handleProgress(e);

  }

  function handleProgress(e, isAction = true) {
    let { pageX, pageY } = e.changedTouches.length && e.changedTouches[0];
    const xRange = [20, 335];
    let differ = pageX - xRange[0];
    if (differ < 0) {
      differ = 0;
    } else if (differ > xRange[1]) {
      differ = xRange[1];
    }
    const percent = differ / (xRange[1] - xRange[0]);
    const value = Number((brightRange[1] * percent).toFixed());
    setBrightPercent(Number((percent * 100).toFixed()));
    console.log(brightPercent, 'brightPercent brightPercent');
    if (isAction) {
      brightAction.set(value);
    }
  }

  return (
    <View
      className={styles.modalback}
      style={{
        background: 'rgba(0, 0, 0, 0.1)',
        backdropFilter: 'blur(35px)',
        visibility: isShow ? 'visible' : 'hidden',
      }}
    >
      <View className={styles.lightModal}>
        <View className={styles.lightModalTop}>
          <View className={styles.lightCloseBg}>Light</View>
          <View className={styles.lightCloseBg}>
            <Image
              className={styles.lightModalClose}
              src={iconClose}
              onClick={() => {
                setModal(false);
              }}
            ></Image>
          </View>
        </View>
        <View
          className={styles.lightMiddle}
          onTouchStart={touchStart}
          onTouchMove={handleTouch}
          onTouchEnd={touchEnd}
        ></View>
        <View
          className={styles.progressBg}
          onTouchStart={progressStart}
          onTouchMove={progressMove}
          onTouchEnd={progressEnd}
        >
          <Image className={styles.progressSun} src={iconSun}></Image>
          <View className={styles.progressTitle}>{brightPercent}%</View>
          <View
            className={styles.progressBar}
            style={{
              width: brightPercent - 0.5 + '%',
              borderBottomRightRadius: brightPercent == 100 ? '16px' : '0',
            }}
          ></View>
        </View>
        <View
          className={styles.lightBtn}
          style={{ backgroundColor: switchVal ? '#6395F6' : 'rgba(0,0,0,0.5)' }}
          onClick={handleLightOn}
        >
          <Image className={styles.lightBtnIcon} src={iconLightWhite}></Image>
          <View className={styles.lightBtnTitle}>{switchVal ? 'ON' : 'OFF'}</View>
          <View className={styles.lightBtnSubtitle}>{switchVal ? '/OFF' : '/ON'}</View>
        </View>
      </View>
      <View
        className={styles.moveCircle}
        style={{
          top: point.pageY - 14 + 'px',
          left: point.pageX - 14 + 'px',
          backgroundColor: 'transparent',
        }}
      ></View>
    </View>
  );
});
