import React, { useState, useRef, useEffect } from 'react';
import { ResizeBox, Tabs } from '@arco-design/web-react';
import styles from './style/logBar.module.less';
import { updateLogBarStatus } from '@/store/ideContainer';
import { useSelector, useDispatch } from 'react-redux';

const TabPane = Tabs.TabPane;

interface LogBarProps {
  a?: string;
}

const data = [
  {
    key: '1',
    title: '运行日志',
    content: '运行时日志...'
  },
  {
    key: '2',
    title: '校验日志',
    content: '校验日志...'
  },
  {
    key: '3',
    title: '流程运行日志',
    content: '流程运行时日志...'
  },
  {
    key: '4',
    title: '组件日志',
    content: '组件日志...'
  }
];

const LogBar: React.FC<LogBarProps> = () => {
  const [tabs] = useState(data);
  const [activeTab, setActiveTab] = useState('1');
  const resizeBoxRef = useRef<HTMLDivElement>(null); // 引用 ResizeBox 容器
  const { logBarStatus } = useSelector((state) => state.ideContainer);
  const dispatch = useDispatch();


  // 处理 Tab 点击事件
  const handleTabClick = (key: string) => {
    // 如果点击当前激活的 tab，则切换收起状态
    if (key === activeTab) {
      dispatch(updateLogBarStatus(!logBarStatus));
    }
    else {
      // 如果点击的是其他 tab，则切换到该 tab 并展开
      setActiveTab(key);
      dispatch(updateLogBarStatus(true));
    }
  };

  // 当 collapsed 状态改变时，直接更新元素的样式
  useEffect(() => {

    if (resizeBoxRef.current) {
      console.log('logBarStatus:', logBarStatus);
      resizeBoxRef.current.style.height = logBarStatus ? '250px' : '0px';
    }
  }, [logBarStatus]);

  // 处理 ResizeBox 手动调整大小事件
  const handleResize = (e: MouseEvent, size: {
    width: number;
    height: number;
  }) => {
    // 当高度接近收起状态的高度时，同步更新 logBarStatus 状态
    if (size.height <= 40) {
      dispatch(updateLogBarStatus(false));
    }
    else {
      dispatch(updateLogBarStatus(true));
    }
  };

  return (
    <>
      <ResizeBox
        ref={resizeBoxRef}
        className={styles.logBar}
        directions={['top']}
        style={{
          height: logBarStatus ? '250px' : '0px'
        }}
        onMoving={handleResize}
      >
        <Tabs
          type="card-gutter"
          activeTab={activeTab}
          onClickTab={handleTabClick}
        >
          {tabs.map((x) => (
            <TabPane destroyOnHide key={x.key} title={x.title}>
              {x.content}
            </TabPane>
          ))}
        </Tabs>
      </ResizeBox>
    </>
  );
};

export default LogBar;