import { Text, View, Swiper, SwiperItem } from '@ray-js/components';
// import {
//   getSystemInfo,
//   onNetworkStatusChange,
//   offNetworkStatusChange,
//   onBluetoothAdapterStateChange,
//   offBluetoothAdapterStateChange,
//   showToast,
//   showLoading,
//   hideLoading,
//   getAppInfo,
//   bluetoothIsPowerOn,
//   publishDps,
//   getDeviceInfo,
//   openDeviceDetailPage,
//   openTimerPage,
// } from '@ray-js/api';
// import { hooks } from '@ray-js/panel-sdk';
import { router, usePageEvent, setNavigationBarTitle, Slider } from '@ray-js/ray';
import React from 'react';
import { useSelector } from '@/redux';
import styles from './index.module.less';
import { Image} from '@ray-js/components';
import iconTempr from '../../../public/icon-temperature.png';
import iconFanBg from '../../../public/icon-fan-bg.png';
import iconFan from '../../../public/icon-fan.png';
import iconOpen from '../../../public/icon-open.png';
import iconSleep from '../../../public/icon-sleep.png';
import iconLight from '../../../public/icon-light.png';
import iconVertical from '../../../public/icon-vertical.png';
import iconOpenOff from '../../../public/icon-open-off.png';
import middleware from '../../../public/icon-middleware.png';

import nature from '../../../public/icon-nature.png';
import natureOn from '../../../public/icon-nature-on.png';
import moon from '../../../public/icon-moon.png';
import moonOn from '../../../public/icon-moon-on.png';
import fresh from '../../../public/icon-fresh.png';
import freshOn from '../../../public/icon-fresh-on.png';
import smart from '../../../public/icon-smart.png';
import smartOn from '../../../public/icon-smart-on.png';
import hand from '../../../public/icon-hand.png';
import handOn from '../../../public/icon-hand-on.png';
import mode from '../../../public/icon-mode.png';
import modeOn from '../../../public/icon-mode-on.png';

import { useState, useEffect } from 'react';
import { LightPanel, FanVertical } from '@/components';
import { useSdmProps, useSdmDevice } from '@ray-js/panel-sdk';
import { devices } from '@/devices';
import { DpBooleanAction, DpCommonAction } from '@ray-js/panel-sdk';

export function Home() {
  const deviceName = useSdmDevice(d => d.devInfo.name);
  useEffect(() => {
    setNavigationBarTitle({ title: deviceName });
  }, [deviceName]);

  const fanSwitchCode = 'switch';
  const fanSpeedCode = 'fan_speed';
  const fanModeCode = 'mode';

  const currentTempCode = 'temp_current';
  const isOpen = useSdmProps(props => {
    return Boolean(props[fanSwitchCode]);
  });
  const fanSpeedVal = useSdmProps(props => {
    return Number(props[fanSpeedCode])
  });
  const [sliderValue,  setSliderValue] = useState(fanSpeedVal);
  useEffect(() => {
    if (fanSpeedVal !== sliderValue) {
      setSliderValue(fanSpeedVal)
    }
  }, [fanSpeedVal])
  const fanModeVal = useSdmProps(props => props[fanModeCode]);

  const currentTempVal = useSdmProps(props => props[currentTempCode]);

  const device = devices.fan;
  const actions = device.model.actions;
  const switchAction = actions[fanSwitchCode] as DpBooleanAction;
  const speedAction = actions[fanSpeedCode] as DpCommonAction<number>;
  const fanModeAction = actions[fanModeCode] as DpCommonAction<string>;

  

  const menu = [
    {
      title: 'Switch',
      icon: iconOpen,
      offIcon: iconOpenOff,
    },
    {
      title: 'Sleep',
      icon: iconSleep,
    },
    {
      title: 'Light',
      icon: iconLight,
    },
    {
      title: 'Vertical',
      icon: iconVertical,
    },
  ];

  const firstMenu = [
    {
      title: 'Nature',
      icon: natureOn,
      offIcon: nature,
      id: 0,
      mode: 'nature',
    },
    {
      title: 'Sleep',
      icon: moonOn,
      offIcon: moon,
      id: 1,
      mode: 'sleep',
    },
    {
      title: 'Fresh',
      icon: freshOn,
      offIcon: fresh,
      id: 2,
      mode: 'fresh',
    },
    {
      title: 'Smart',
      icon: smartOn,
      offIcon: smart,
      id: 3,
      mode: 'smart',
    },
  ];

  const secondMenu = [
    // {
    //   title:'Nature',
    //   icon:handOn,
    //   offIcon: hand,
    //   id: 4
    // },
    {
      title: 'Strong',
      icon: modeOn,
      offIcon: mode,
      id: 4,
      mode: 'strong',
    },
  ];

  const [menuIndex, setMenuIndex] = useState(null);
  // const [preTime, setPreTime] = useState(null)
  const [isShowModal, setModal] = useState(false);

  function spinDuration() {
    if (fanSpeedVal == 0) {
      return '0s';
    } else {
      return 2 - ((2 - 0.2) / 100) * fanSpeedVal + 's';
    }
  }

  function clickMenu(e) {
    const index = e.currentTarget.id;
    if (index == 0) {
      switchAction.toggle();
      setMenuIndex(null);
    } else if (isOpen) {
      if (index == 2) {
        setMenuIndex(null);
        setModal(true);
      } else {
        if (index == menuIndex) {
          setMenuIndex(null);
        } else {
          setMenuIndex(index);
        }
      }
    }
  }

  function handleSubmenu(mode) {
    if (mode !== fanModeVal) {
      fanModeAction.set(mode);
    }
  }

  function SubmenuItem(item, clickFun = handleSubmenu, currentIndex = fanModeVal) {
    const { title, mode, icon, offIcon, id } = item;
    return (
      <View className={styles.button} key={item.id}>
        <Image
          className={styles.menuImage}
          src={mode == currentIndex ? icon : offIcon}
          onClick={() => {
            clickFun(mode);
          }}
        />
        <Text className={styles.bTitle}>{title}</Text>
      </View>
    );
  }

  const toggleModal = e => {
    console.log(e, 'toggleModal');
    //  setModal(false)
    setMenuIndex(null);
  };

  const stopFurtherClick = e => {
    console.log(e, 'stopFurtherClick');
    e.origin.stopPropagation();
  };

  const modalSetting = {
    show: true,
    position: 'center',
    overlay: true,
    onClickOverlay: toggleModal,
    overlayStyle: { backgroundColor: 'transparent' },
  };

  return (
    <View className={styles.page}>
      <View className={styles.header}>
        <View className={styles.alignCenter}>
          <Image className={styles.icon} src={iconTempr} />
          <View className={styles.title}>{currentTempVal}°C</View>
        </View>
        {/* <View className={styles.timer}>Countdown to open 03:00</View> */}
      </View>
      <View className={styles.fanGroup}>
        <Image className={styles.fanBg} src={iconFanBg}></Image>
        <Image
          className={styles.fan}
          src={iconFan}
          style={{
            animationDuration: spinDuration(),
            animationPlayState: isOpen ? 'running' : 'paused',
          }}
        ></Image>
      </View>
      <View className={styles.sliderBg}>
        <Slider
          activeColor="linear-gradient(-90deg, #87ABF2 11.62%, #4B7EE2 100%)"
          blockColor="white"
          blockSize={28}
          min={1}
          max={100}
          value={sliderValue}
          step={5}
          disabled={!isOpen}
          onChange={e => {
            speedAction.set(e.value);
          }}
          onChanging={e => {
            setSliderValue(e.value);
          }}
        />
        <View className={styles.fantBottom}>
          <View className={styles.fontBottomTint}>Fan Speed</View>
          <View className={styles.fontBottomTint}>{sliderValue}</View>
        </View>
      </View>
      <View className={styles.flexRowBetween}>
        {menu.map(({ title, icon, offIcon }, index) => {
          return (
            <View className={styles.button} key={index}>
              <Image
                className={styles.middleware}
                src={middleware}
                style={{ visibility: menuIndex == index ? 'visible' : 'hidden' }}
              />
              <Image
                src={index > 0 ? icon : isOpen ? icon : offIcon}
                className={styles.menuImage}
                id={String(index)}
                style={{ opacity: isOpen ? 1 : index > 0 ? 0.4 : 1 }}
                onClick={clickMenu}
              ></Image>
              <Text className={styles.bTitle}>{title}</Text>
            </View>
          );
        })}
      </View>
      {menuIndex == 1 && (
        <View className={styles.modalOverlay} onClick={toggleModal}>
          <View className={styles.modalBg} onClick={stopFurtherClick}>
            <Swiper dots={true} dotActiveColor="#6395F6" dotColor="rgba(99,149,246, 0.2)">
              <SwiperItem>
                <View className={styles.swiperItem}>
                  {firstMenu.map(item => SubmenuItem(item))}
                </View>
              </SwiperItem>
              <SwiperItem>
                <View className={styles.swiperItemNext}>
                  {secondMenu.map(item => SubmenuItem(item))}
                </View>
              </SwiperItem>
            </Swiper>
          </View>
        </View>
      )}
      {menuIndex == 3 && (
        <View className={styles.modalOverlay} onClick={toggleModal}>
          <View
            className={styles.modalBg}
            style={{
              height: '213px',
              display: 'flex',
              flexDirection: 'column',
              padding: '16px 16px 0',
              gap: '12px',
              bottom: '140px',
            }}
            onClick={stopFurtherClick}
          >
            <FanVertical></FanVertical>
          </View>
        </View>
      )}
      <LightPanel isShow={isShowModal} setModal={setModal}></LightPanel>
    </View>
  );
}

export default Home;
