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 { ExperimentCompleted } from '@/utils/constant';
import { formatDate } from '@/utils/date';
import { getWorkflowStatus } from '@/utils/experiment';
import { Typography } from 'antd';
import React, { useCallback } from 'react';
import styles from './index.less';

type ExperimentInstanceComponentProps = {
  instance: ExperimentInstance;
};

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

  const handleSSEMessage: MessageHandler = useCallback(
    (experimentId: number, experimentInsId: number, status: string, finishTime: string) => {
      window.postMessage({
        type: ExperimentCompleted,
        payload: {
          experimentId,
          experimentInsId,
          status,
          finishTime,
        },
      });
    },
    [],
  );
  useSSE(experiment_id, id, status, argo_ins_name, argo_ins_ns, handleSSEMessage);

  return (
    <React.Fragment>
      <div className={styles.description}>
        <div style={{ width: '50%' }}>
          <RunDuration createTime={createTime} finishTime={finishTime} />
        </div>
        <div style={{ width: '50%' }} className={styles.startTime}>
          <Typography.Text ellipsis={{ tooltip: formatDate(createTime) }}>
            {formatDate(createTime)}
          </Typography.Text>
        </div>
      </div>
      <div className={styles.statusBox}>
        {statusInfo ? (
          <>
            <img
              style={{ width: '17px', marginRight: '7px' }}
              src={statusInfo.icon}
              draggable={false}
              alt=""
            />
            <span style={{ color: statusInfo.color }}>{statusInfo.label}</span>
          </>
        ) : (
          '--'
        )}
      </div>
    </React.Fragment>
  );
}

export default ExperimentInstanceComponent;
