import { useMemo } from "react";
import type { FC } from "react";
import { FlowChart } from "../FlowChart/FlowChart";
import { useTrace } from "../../hooks/useTrace";
import { useFlowChartData } from "../FlowChart/hooks/useFlowChartData";
import type { Goal } from "../../types/goal";
import type { Edge } from "../../types/message";
import styles from "./MainContent.module.css";

interface MainContentProps {
  traceId: string | null;
  onNodeClick?: (node: Goal, edge?: Edge) => void;
}

export const MainContent: FC<MainContentProps> = ({ traceId, onNodeClick }) => {
  const { trace, loading } = useTrace(traceId);
  const initialGoals = useMemo(() => trace?.goal_tree?.goals ?? [], [trace]);
  const { goals, connected, msgGroups } = useFlowChartData(traceId, initialGoals);

  if (!traceId && !loading) {
    return (
      <div className={styles.main}>
        <div className={styles.header}>
          <div className={styles.title}>暂无 Trace</div>
          <div className={styles.status}>未连接</div>
        </div>
        <div className={styles.content}>
          <div className={styles.empty}>暂无可展示的数据</div>
        </div>
      </div>
    );
  }

  return (
    <div className={styles.main}>
      <div className={styles.header}>
        <div className={styles.title}></div>
        <div className={styles.headerRight}>
          <div className={styles.status}>{connected ? "WebSocket 已连接" : "WebSocket 未连接"}</div>
          <div className={styles.legend}>
            <div className={styles.legendItem}>
              <span
                className={styles.legendDot}
                style={{ background: "#00c853" }}
              />
              已完成
            </div>
            <div className={styles.legendItem}>
              <span
                className={styles.legendDot}
                style={{ background: "#f44336" }}
              />
              失败
            </div>
            <div className={styles.legendItem}>
              <span
                className={styles.legendDot}
                style={{ background: "#ff9800" }}
              />
              运行中
            </div>
            <div className={styles.legendItem}>
              <span
                className={styles.legendDot}
                style={{ background: "#4e79a7" }}
              />
              默认
            </div>
          </div>
        </div>
      </div>
      <div className={styles.content}>
        {loading ? (
          <div className={styles.empty}>加载中...</div>
        ) : goals.length === 0 ? (
          <div className={styles.empty}>暂无节点</div>
        ) : (
          <FlowChart
            goals={goals}
            msgGroups={msgGroups}
            onNodeClick={onNodeClick}
          />
        )}
      </div>
    </div>
  );
};
