import { PageContainer, ProCard } from '@ant-design/pro-components';
import { Table, Space, Button, notification, Modal } from 'antd';
import { useEffect, useState } from 'react';
import type { ColumnsType } from 'antd/es/table';

interface TestRun {
  key: number;
  id: number;
  name: string;
  params: string;
}

export default () => {
  const [tableData, setTableData] = useState<TestRun[]>([]);

  const columns: ColumnsType<TestRun> = [
    {
      title: 'ID',
      dataIndex: 'id',
    },
    {
      title: 'Test Run Name',
      dataIndex: 'name',
    },
    {
      title: 'Params',
      dataIndex: 'params',
      render: (text, record) => JSON.stringify(record.params),
    },
  ];

  function openRequestErrorNotification(url: string, statusText: string) {
    notification.error({
      message: 'Error',
      description: 'fetch ' + url + ' got ' + statusText,
    });
  }

  function openBackendNotification(error: Error) {
    notification.error({
      message: 'Error',
      description: error,
    });
  }

  useEffect(() => {
    fetch('/api/v1/runs')
      .then((res) => {
        if (res.status != 200) {
          res.json().then(
            (result) => {
              openBackendNotification(result.error);
            },
            (error) => {
              openRequestErrorNotification(res.url, res.statusText);
            },
          );
          throw new Error('Request Error');
        }
        return res.json();
      })
      .then(
        (result) => {
          let data: TestRun[] = [];
          for (const i of result.result.runs) {
            data.push({
              key: i.run.ID,
              id: i.run.ID,
              name: i.run.name,
              params: i.run.params,
            });
          }

          setTableData(data);
        },
        (error) => {
          console.log(error);
        },
      );
  }, []);

  return (
    <PageContainer>
      <ProCard ghost gutter={8}>
        <ProCard
          style={{ minHeight: '90vh', height: '100px', overflowY: 'scroll' }}
          colSpan={24}
          bordered
        >
          <Table
            pagination={{ defaultPageSize: 20 }}
            columns={columns}
            dataSource={tableData}
          />
        </ProCard>
      </ProCard>
    </PageContainer>
  );
};
