import React, { memo, useEffect } from 'react';
import ScreenWrap from './index';
import Animation from './Animation';

const MAX_DELAY = 2147483;

const Panel = memo(
  ({
    id,
    config,
    states,
    iState,
    iActiveState,
    switchPanelState,
    screenConfig,
  }: {
    id: string;
    config: {
      left: number;
      top: number;
      width: number;
      height: number;
      allowScroll: boolean;
      autoCarousel: boolean;
      interval: number;
    };
    states: number[];
    iState: any;
    iActiveState: any;
    screenConfig: { screenId: number; screenPassword: string }[];
    switchPanelState?: (id: string) => void;
  }) => {
    const { left, top, width, height, allowScroll, autoCarousel, interval } = config;

    useEffect(() => {
      let timer;
      if (autoCarousel && states.length > 1) {
        timer = setInterval(() => {
          switchPanelState && switchPanelState(id);
        }, (interval >= MAX_DELAY ? MAX_DELAY : interval) * 1000);
      }
      return () => {
        timer && clearInterval(timer);
      };
    }, []);

    const current = iState?.stateId || states[0];

    return (
      <Animation
        id={id}
        iState={iState}
        iActiveState={iActiveState}
        width={width}
        height={height}
        top={top}
        left={left}>
        <div
          id={id}
          style={{
            position: 'absolute',
            width,
            height,
            top,
            left,
            overflow: allowScroll ? 'auto' : 'hidden',
            pointerEvents: allowScroll ? 'auto' : 'none',
          }}>
          {states.map((d, i) => {
            const currentState = (iState && iState[d]) || {};
            const { unmount = true, animation } = currentState;
            const userSetPassword = screenConfig.find((o) => o.screenId === d)?.screenPassword;
            return (
              <Animation
                key={i}
                id={d}
                iState={{ key: 'show', show: current === d ? true : false, unmount }}
                width={width}
                height={height}
                iActiveState={animation ? { animation } : undefined}
                top={0}
                left={0}>
                  <ScreenWrap id={d} width={width} height={height} userSetPassword={userSetPassword} />
              </Animation>
            );
          })}
        </div>
      </Animation>
    );
  },
);
export default Panel;
