import TableColTitle from '@/components/TableColTitle';
import {
  getReqParamName,
  type FormParameter,
} from '@/pages/HyperParameter/components/CreateForm/utils';
import { HyperParameterData } from '@/pages/HyperParameter/types';
import tableCellRender, { TableCellValueType } from '@/utils/table';
import { Table, type TableProps } from 'antd';
import { useMemo } from 'react';
import styles from './index.less';

type ParameterInfoProps = {
  info: HyperParameterData;
};

function ParameterInfo({ info }: ParameterInfoProps) {
  const parameters = useMemo(() => {
    if (!info.parameters) {
      return [];
    }
    return info.parameters.map((item) => {
      const paramName = getReqParamName(item.type);
      const range = item[paramName];
      return {
        ...item,
        range,
      };
    });
  }, [info]);

  const runParameters = useMemo(() => {
    if (!info.points_to_evaluate) {
      return [];
    }
    return info.points_to_evaluate.map((item, index) => ({
      ...item,
      id: index, // 作为 key，这个数组不会变化
    }));
  }, [info]);

  const columns: TableProps<FormParameter>['columns'] = [
    {
      title: '参数名称',
      dataIndex: 'name',
      key: 'type',
      width: '40%',
      render: tableCellRender('auto'),
    },
    {
      title: '参数类型',
      dataIndex: 'type',
      key: 'type',
      width: '20%',
      render: tableCellRender(false),
    },
    {
      title: '取值范围',
      dataIndex: 'range',
      key: 'range',
      width: '40%',
      render: tableCellRender(true, TableCellValueType.Custom, {
        format: (value) => {
          return JSON.stringify(value);
        },
      }),
    },
  ];

  const runColumns: TableProps<Record<string, any>>['columns'] =
    runParameters.length > 0
      ? parameters.map(({ name }) => {
          return {
            title: <TableColTitle title={name} />,
            dataIndex: name,
            key: name,
            width: 150,
            render: tableCellRender(true),
          };
        })
      : [];

  return (
    <div className={styles['parameter-info']}>
      <div className={styles['parameter-info__title']}>超参数</div>
      <Table
        dataSource={parameters}
        columns={columns}
        rowKey="name"
        bordered
        pagination={false}
        tableLayout="fixed"
      />
      <div className={styles['parameter-info__title']}>手动运行超参数</div>
      <Table
        dataSource={runParameters}
        columns={runColumns}
        rowKey="id"
        bordered
        pagination={false}
        scroll={{ x: '100%' }}
        tableLayout="fixed"
      />
    </div>
  );
}

export default ParameterInfo;
