import { myLocalStorage } from '@tingwu/common';
import { SummaryErrorText, useSphereState } from '@tingwu/sphere';

import {
  docBigModelHooks,
  documentHooks,
} from '../../../../../../../documentModel';
import { eLabInfoStatus } from '../../../../../../../documentModel/docBigModel';
import { useDataHooks } from '../../../../../../../pages/docASR/components/businessCommon/separateHooks/dataShare';
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { MultiEllipsis } from '../multiEllipsis';
import { SphereCard } from '../sphereCard';
import { HideDiv } from './styled';

export const MeetingSummaryCard = memo(() => {
  const {
    documentData: { docId: transId },
  } = documentHooks.useDocumentData();

  const { meetingSummaryController } = useDataHooks();
  const fullContentRef = useRef<HTMLDivElement>(null);
  const content = useSphereState(meetingSummaryController, 'content');
  const [isShowRedDot, setIsShowRedDot] = useState(false);
  const inspectShowRedDot = true;
  const { currentDocBigModelData } = docBigModelHooks.useDocBigModelData();
  const { fullTextSummaryStatus } = currentDocBigModelData || {};
  const isTextTooShort =
    fullTextSummaryStatus === eLabInfoStatus.TEXT_TOO_SHORT;
  const isFail = fullTextSummaryStatus === eLabInfoStatus.FAILED;
  const errorText = isTextTooShort ? '抱歉，全文内容太短了，无总结内容哦' : '';
  useEffect(() => {
    if (inspectShowRedDot) {
      setIsShowRedDot(
        !myLocalStorage.isHasId(
          'showedMeetingSummaryExpanderV2',
          transId as any,
        ),
      );
    }
  }, [inspectShowRedDot, transId]);

  const handleExpanded = useCallback(() => {
    myLocalStorage.setItemById(
      'showedMeetingSummaryExpanderV2',
      transId as any,
    );

    setIsShowRedDot(
      !myLocalStorage.isHasId('showedMeetingSummaryExpanderV2', transId as any),
    );
  }, [transId]);

  const renderedContent = useMemo(() => {
    if (errorText) {
      return <SummaryErrorText text={errorText} />;
    }
    if (isFail) {
      return <SummaryErrorText isFail />;
    }
    if (!content) {
      return <SummaryErrorText isEmpty />;
    }
    return (
      <div style={{ position: 'relative' }}>
        <MultiEllipsis
          text={content}
          showRedDot={isShowRedDot}
          onExpand={handleExpanded}
          expandDefult={false}
          showExpend={false}
        />
        <HideDiv ref={fullContentRef}>{content}</HideDiv>
      </div>
    );
  }, [isFail, content, errorText, isShowRedDot, handleExpanded]);

  return <SphereCard content={renderedContent} />;
});
