import KFIcon from '@/components/KFIcon';
import { ExperimentStatus } from '@/enums';
import { experimentStatusInfo } from '@/pages/Experiment/status';
import {
  deleteQueryByExperimentInsId,
  putQueryByExperimentInsId,
} from '@/services/experiment/index.js';
import themes from '@/styles/theme.less';
import { type ExperimentInstance } from '@/types';
import { elapsedTime, formatDate } from '@/utils/date';
import { to } from '@/utils/promise';
import { modalConfirm } from '@/utils/ui';
import { DoubleRightOutlined } from '@ant-design/icons';
import { App, Button, ConfigProvider, Tooltip } from 'antd';
import classNames from 'classnames';
import TensorBoardStatusCell from '../TensorBoardStatus';
import styles from './index.less';

type ExperimentInstanceProps = {
  experimentInList?: ExperimentInstance[];
  experimentInsTotal: number;
  onClickInstance?: (instance: ExperimentInstance) => void;
  onClickTensorBoard?: (instance: ExperimentInstance) => void;
  onRemove?: () => void;
  onTerminate?: (instance: ExperimentInstance) => void;
  onLoadMore?: () => void;
};

function ExperimentInstanceComponent({
  experimentInList,
  experimentInsTotal,
  onClickInstance,
  onClickTensorBoard,
  onRemove,
  onTerminate,
  onLoadMore,
}: ExperimentInstanceProps) {
  const { message } = App.useApp();

  // 删除实验实例确认
  const handleRemove = (instance: ExperimentInstance) => {
    modalConfirm({
      title: '确定删除该条实例吗？',
      onOk: () => {
        deleteExperimentInstance(instance.id);
      },
    });
  };

  // 删除实验实例
  const deleteExperimentInstance = async (id: number) => {
    const [res] = await to(deleteQueryByExperimentInsId(id));
    if (res) {
      message.success('删除成功');
      onRemove?.();
    }
  };

  // 终止实验实例
  const terminateExperimentInstance = async (instance: ExperimentInstance) => {
    const [res] = await to(putQueryByExperimentInsId(instance.id));
    if (res) {
      message.success('终止成功');
      onTerminate?.(instance);
    }
  };

  if (!experimentInList || experimentInList.length === 0) {
    return null;
  }

  return (
    <div>
      <div className={styles.tableExpandBox} style={{ paddingBottom: '16px' }}>
        <div className={styles.index}>序号</div>
        <div className={styles.tensorBoard}>可视化</div>
        <div className={styles.description}>
          <div style={{ width: '50%' }}>运行时长</div>
          <div style={{ width: '50%' }}>开始时间</div>
        </div>
        <div className={styles.status}>状态</div>
        <div className={styles.operation}>操作</div>
      </div>

      {experimentInList.map((item, index) => (
        <div
          key={item.id}
          className={classNames(styles.tableExpandBox, styles.tableExpandBoxContent)}
        >
          <a
            className={styles.index}
            style={{ padding: '0 16px' }}
            onClick={() => onClickInstance?.(item)}
          >
            {index + 1}
          </a>
          <div className={styles.tensorBoard}>
            {item.nodes_result?.tensorboard_log ? (
              <TensorBoardStatusCell
                status={item.tensorBoardStatus}
                onClick={() => onClickTensorBoard?.(item)}
              ></TensorBoardStatusCell>
            ) : (
              '--'
            )}
          </div>
          <div className={styles.description}>
            <div style={{ width: '50%' }}>{elapsedTime(item.create_time, item.finish_time)}</div>
            <div style={{ width: '50%' }} className={styles.startTime}>
              <Tooltip title={formatDate(item.create_time)}>
                <span>{formatDate(item.create_time)}</span>
              </Tooltip>
            </div>
          </div>
          <div className={styles.statusBox}>
            <img
              style={{ width: '17px', marginRight: '7px' }}
              src={experimentStatusInfo[item.status as ExperimentStatus]?.icon}
            />
            <span
              style={{ color: experimentStatusInfo[item.status as ExperimentStatus]?.color }}
              className={styles.statusIcon}
            >
              {experimentStatusInfo[item.status as ExperimentStatus]?.label}
            </span>
          </div>
          <div className={styles.operation}>
            <Button
              type="link"
              size="small"
              key="stop"
              disabled={
                item.status === ExperimentStatus.Succeeded ||
                item.status === ExperimentStatus.Failed ||
                item.status === ExperimentStatus.Terminated
              }
              icon={<KFIcon type="icon-zhongzhi" />}
              onClick={() => terminateExperimentInstance(item)}
            >
              终止
            </Button>
            <ConfigProvider
              theme={{
                token: {
                  colorLink: themes['warningColor'],
                },
              }}
            >
              <Button
                type="link"
                size="small"
                key="batchRemove"
                disabled={
                  item.status === ExperimentStatus.Running ||
                  item.status === ExperimentStatus.Pending
                }
                icon={<KFIcon type="icon-shanchu" />}
                onClick={() => handleRemove(item)}
              >
                删除
              </Button>
            </ConfigProvider>
          </div>
        </div>
      ))}
      {experimentInsTotal > experimentInList.length ? (
        <div className={styles.loadMoreBox}>
          <Button type="link" onClick={onLoadMore}>
            更多
            <DoubleRightOutlined rotate={90} />
          </Button>
        </div>
      ) : null}
    </div>
  );
}

export default ExperimentInstanceComponent;
