import KFIcon from '@/components/KFIcon';
import { ExperimentStatus } from '@/enums';
import { useCheck } from '@/hooks/useCheck';
import {
  deleteManyExperimentIns,
  deleteQueryByExperimentInsId,
  putQueryByExperimentInsId,
} from '@/services/experiment/index.js';
import themes from '@/styles/theme.less';
import { type ExperimentInstance } from '@/types';
import { to } from '@/utils/promise';
import { modalConfirm } from '@/utils/ui';
import { DoubleRightOutlined } from '@ant-design/icons';
import { App, Button, Checkbox, ConfigProvider } from 'antd';
import classNames from 'classnames';
import { useEffect, useMemo } from 'react';
import TensorBoardStatusCell from '../TensorBoardStatus';
import styles from './index.less';
import ExperimentInstanceComponent from './instance';

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

function ExperimentInstanceList({
  experimentInsList,
  experimentInsTotal,
  onClickInstance,
  onClickTensorBoard,
  onRemove,
  onTerminate,
  onLoadMore,
}: ExperimentInstanceListProps) {
  const { message } = App.useApp();
  const allIntanceIds = useMemo(() => {
    return (
      experimentInsList
        ?.filter(
          (item) =>
            item.status !== ExperimentStatus.Running && item.status !== ExperimentStatus.Pending,
        )
        .map((item) => item.id) || []
    );
  }, [experimentInsList]);
  const [
    selectedIns,
    setSelectedIns,
    checked,
    indeterminate,
    checkAll,
    isSingleChecked,
    checkSingle,
  ] = useCheck(allIntanceIds);

  useEffect(() => {
    // 关闭时清空
    if (allIntanceIds.length === 0) {
      setSelectedIns([]);
    }
  }, [allIntanceIds, setSelectedIns]);

  // 删除实验实例确认
  const handleRemove = (instance: ExperimentInstance) => {
    modalConfirm({
      title: '删除后，该实验实例将不可恢复',
      content: '是否确认删除?',
      onOk: () => {
        deleteExperimentInstance(instance.id);
      },
    });
  };

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

  // 批量删除实验实例确认
  const handleDeleteAll = () => {
    modalConfirm({
      title: '确定批量删除选中的实例吗？',
      onOk: () => {
        batchDeleteExperimentInstances();
      },
    });
  };

  // 批量删除实验实例
  const batchDeleteExperimentInstances = async () => {
    const [res] = await to(deleteManyExperimentIns(selectedIns));
    if (res) {
      message.success('删除成功');
      setSelectedIns([]);
      onRemove?.();
    }
  };

  // 终止实验实例
  const handleTerminate = (instance: ExperimentInstance) => {
    modalConfirm({
      title: '终止后，该次实验运行将不可恢复',
      content: '是否确认终止?',
      isDelete: false,
      onOk: () => {
        terminateExperimentInstance(instance);
      },
    });
  };

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

  if (!experimentInsList || experimentInsList.length === 0) {
    return <div style={{ textAlign: 'center' }}>暂无数据</div>;
  }

  return (
    <div>
      <div className={styles.tableExpandBox} style={{ paddingBottom: '16px' }}>
        <div className={styles.check}>
          <Checkbox
            checked={checked}
            indeterminate={indeterminate}
            disabled={allIntanceIds.length === 0}
            onChange={checkAll}
          ></Checkbox>
        </div>
        <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}>
          <span>操作</span>
          {selectedIns.length > 0 && (
            <Button
              style={{ position: 'absolute', right: '0' }}
              color="primary"
              variant="filled"
              size="small"
              onClick={handleDeleteAll}
              icon={<KFIcon type="icon-shanchu" />}
            >
              删除
            </Button>
          )}
        </div>
      </div>

      {experimentInsList.map((item, index) => (
        <div
          key={item.id}
          className={classNames(styles.tableExpandBox, styles.tableExpandBoxContent)}
        >
          <div className={styles.check}>
            <Checkbox
              checked={isSingleChecked(item.id)}
              onChange={() => checkSingle(item.id)}
              disabled={
                item.status === ExperimentStatus.Running || item.status === ExperimentStatus.Pending
              }
            ></Checkbox>
          </div>
          <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>

          <ExperimentInstanceComponent instance={item}></ExperimentInstanceComponent>

          <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={() => handleTerminate(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 > experimentInsList.length ? (
        <div className={styles.loadMoreBox}>
          <Button type="link" onClick={onLoadMore}>
            更多
            <DoubleRightOutlined rotate={90} />
          </Button>
        </div>
      ) : null}
    </div>
  );
}

export default ExperimentInstanceList;
