import React, { memo, useRef, useCallback, useMemo, useState, useEffect } from "react";
import { MeetingSummaryController } from "../../spheres/meetingSummary/meetingSummaryController";
import { SphereCard } from "../sphereCard";
import { useSphereState } from "../provider";
import { HideDiv } from "./styled";
import { CopyOperate, FeedbackOperate } from "../sphereCard/operates";
import { myLocalStorage } from "@tingwujs/common";
import { SummaryErrorText } from "../summaryErrorText";
import { MultiEllipsis } from "../multiEllipsis";

export interface MeetingSummaryCardProps {
  meetingSummaryController: MeetingSummaryController;
  onShowFeedback?: () => void;
  isFail?: boolean;
  showOperates?: boolean;
  errorText?: string;
  transId?: string;
  title?: React.ReactNode;
  inspectShowRedDot: boolean;
}

export const MeetingSummaryCard: React.FC<MeetingSummaryCardProps> = memo(props => {
  const {
    meetingSummaryController,
    onShowFeedback,
    isFail = false,
    showOperates = true,
    errorText,
    transId = "-",
    title,
    inspectShowRedDot,
  } = props;

  const fullContentRef = useRef<HTMLDivElement>(null);
  const content = useSphereState(meetingSummaryController, "content");
  const [isShowRedDot, setIsShowRedDot] = useState(false);

  useEffect(() => {
    if (inspectShowRedDot) {
      setIsShowRedDot(!myLocalStorage.isHasId("showedMeetingSummaryExpanderV2", transId));
    }
  }, [inspectShowRedDot, transId]);

  const handleExpanded = useCallback(() => {
    myLocalStorage.setItemById("showedMeetingSummaryExpanderV2", transId);

    setIsShowRedDot(!myLocalStorage.isHasId("showedMeetingSummaryExpanderV2", transId));
  }, [transId]);

  const getCopyText = useCallback(() => content || "", [content]);

  const headingOperates = useMemo(() => {
    if (!showOperates) {
      return [];
    }
    const ops = [<FeedbackOperate key="FeedbackOperate" onShowFeedback={onShowFeedback} />];
    if (content) {
      ops.push(<CopyOperate key="CopyOperate" getCopyText={getCopyText} />);
    }
    return ops;
  }, [content, getCopyText, onShowFeedback, showOperates]);

  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}
          lineClamp={3}
          showRedDot={isShowRedDot}
          onExpand={handleExpanded}
        />
        <HideDiv ref={fullContentRef}>{content}</HideDiv>
      </div>
    );
  }, [isFail, content, errorText, isShowRedDot, handleExpanded]);

  return (
    <SphereCard
      title={title || "全文概要"}
      showIcon={false}
      headingOperates={headingOperates}
      content={renderedContent}
    />
  );
});
