import KFIcon from '@/components/KFIcon';
import RunDuration from '@/components/RunDuration';
import { ExperimentStatus } from '@/enums';
import { useSSE, type MessageHandler } from '@/hooks/useSSE';
import { experimentStatusInfo } from '@/pages/Experiment/status';
import { ExperimentInstance, NodeStatus } from '@/types';
import { formatDate } from '@/utils/date';
import { getExperimentInstanceStatus, getWorkflowStatus } from '@/utils/experiment';
import { Button } from 'antd';
import { useCallback, useState } from 'react';
import styles from './index.less';

const NodePrefix = 'workflow';

type ExperimentInstanceComponentProps = {
  instance: ExperimentInstance;
  onClick: () => void;
};

function ExperimentInstanceComponent({ instance, onClick }: ExperimentInstanceComponentProps) {
  const { experiment_id, id, argo_ins_name, argo_ins_ns, nodes_status } = instance;
  const initialWorkflowStatus = getWorkflowStatus(nodes_status) as NodeStatus | undefined;
  const [workflowStatus, setWorkflowStatus] = useState<NodeStatus | undefined>(
    initialWorkflowStatus,
  );
  const status = getExperimentInstanceStatus(instance.status as ExperimentStatus, workflowStatus);
  const createTime = workflowStatus?.startedAt;
  const finishTime = workflowStatus?.finishedAt;
  const statusInfo = experimentStatusInfo[status];

  const handleSSEMessage: MessageHandler = useCallback(
    (
      _experimentId: number,
      _experimentInsId: number,
      _status: string,
      _finishTime: string,
      nodes,
    ) => {
      if (nodes) {
        // 设置总 workflow 状态
        const workflowStatus = Object.values(nodes).find((node: any) =>
          node.displayName.startsWith(NodePrefix),
        ) as NodeStatus;
        if (workflowStatus) {
          setWorkflowStatus(workflowStatus);
        }
      }
    },
    [],
  );
  useSSE(experiment_id, id, status, argo_ins_name, argo_ins_ns, handleSSEMessage);

  return (
    <div className={styles['experiment-table__content']} key={id}>
      <div className={styles['experiment-table__status']} style={{ paddingLeft: '6.5px' }}>
        <img src={statusInfo?.icon} width={17} height={17} draggable={false} alt="" />
      </div>
      <div className={styles['experiment-table__duration']}>
        <RunDuration createTime={createTime} finishTime={finishTime} />
      </div>
      <div className={styles['experiment-table__date']}>{formatDate(createTime)}</div>
      <div className={styles['experiment-table__operation']}>
        <Button
          size="small"
          type="link"
          icon={<KFIcon type="icon-xiangqing2" font={14} />}
          onClick={onClick}
        >
          详情
        </Button>
      </div>
    </div>
  );
}

export default ExperimentInstanceComponent;
