import {
  ContentTabType,
  FileModel,
  INTERPOSITION_DATA,
} from '../../../../../../pages/docASR/utils/config';
import { contentTabActiveState } from '../../../../../../recoils/docFile/file';
import bus from '../../../../../../utils/bus';
import { Radio } from 'antd';
import { Divider } from 'antd';
import { memo, useCallback, useEffect, useRef } from 'react';
import { useRecoilState } from 'recoil';
import styled from 'styled-components';
import { getEditorData } from '../../../businessCommon/constVariable';
import { RadioButtonGroup } from './styled';

const ContentTabContainer = styled.div`
  display: flex;
  height: 52px;
  padding-left: 32px;
  background-color: var(--Fill_Background_Light);
  position: relative;
  border-bottom: 1px solid var(--Line_Light);
  align-items: center;
`;

const TabTitle = styled.span`
  font-size: 16px;
  font-weight: 500;
  line-height: 24px;
  /* 中性色/color-text */
  color: var(--Text_Primary); /* rgba(38, 36, 76, 0.88) */
`;

export interface ContentTabProps {
  fileModel?: FileModel;
  realTabsList: any;
}

const ContentTab = memo(({ realTabsList }: ContentTabProps) => {
  const [contentTabActive, setContentTabActive] = useRecoilState(
    contentTabActiveState,
  );

  const awaitDataCbRef = useRef();
  const awaitData = (cb: any) => {
    const editorInstance = getEditorData('editorRef');
    if (editorInstance) {
      cb();
    } else {
      setTimeout(() => {
        awaitData(cb);
      }, 200);
    }
  };

  useEffect(() => {
    if (contentTabActive !== ContentTabType.note) return;
    if (!awaitDataCbRef.current) return;
    const cb = awaitDataCbRef.current;
    awaitDataCbRef.current = undefined;
    awaitData(cb);
  }, [contentTabActive, awaitDataCbRef.current]);

  const interpositionData = useCallback(
    (cb: any) => {
      if (contentTabActive !== ContentTabType.note) {
        setContentTabActive(ContentTabType.note);
        awaitDataCbRef.current = cb;
        return;
      }
      cb();
    },
    [contentTabActive, setContentTabActive],
  );

  useEffect(() => {
    bus.on(INTERPOSITION_DATA, interpositionData);
    return () => {
      bus.off(INTERPOSITION_DATA, interpositionData);
    };
  }, [interpositionData]);

  return (
    <ContentTabContainer style={{ borderBottom: 0 }}>
      <TabTitle>分析结果</TabTitle>
      <Divider type="vertical" style={{ height: 16, margin: '0 12px' }} />
      <RadioButtonGroup
        value={contentTabActive}
        optionType="button"
        size="small"
        options={realTabsList.map((item) => ({
          label: item.title,
          value: item.type,
        }))}
        onChange={(e) => {
          setContentTabActive(e.target.value);
        }}
      />
    </ContentTabContainer>
  );
});

export default ContentTab;
