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

interface AIModel {
  key: number;
  id: number;
  name: string;
  description: string;
  model_type: string;
}

export default () => {
  const [tableData, setTableData] = useState<AIModel[]>([]);
  const [editModel, setEditModel] = useState<AIModel>();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [pagination, setPagination] = useState({
    pageSize: 20,
    current: 1,
    total: 100,
    onChange: onChange,
  });

  async function onChange(page, pageSize) {
    pagination.pageSize = pageSize;
    pagination.current = page;
    setPagination(pagination);
    loadData();
  }

  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,
    });
  }

  const columns: ColumnsType<AIModel> = [
    {
      title: 'ID',
      dataIndex: 'id',
    },
    {
      title: 'Name',
      dataIndex: 'name',
    },
    {
      title: 'Description',
      dataIndex: 'description',
    },
    {
      title: 'Model Type',
      dataIndex: 'model_type',
    },
    {
      title: 'Action',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button type="primary" onClick={() => handleEditAIModel(record)}>
            Edit
          </Button>
          <Button type="info" onClick={() => handleCreateAIModel(record)}>
            Create
          </Button>
        </Space>
      ),
    },
  ];

  async function handleEditAIModel(record: AIModel) {
    setEditModel(record);

    setIsModalOpen(true);
  }

  async function handleCreateAIModel(_: AIModel) {
    let model: AIModel = {
      key: 0,
      id: 0,
      name: '',
      description: '',
      model_type: '',
    };

    setEditModel(model);
    setIsModalOpen(true);
  }

  function loadData() {
    fetch(
      `/api/v1/ai_models?page=${pagination.current}&per_page=${pagination.pageSize}`,
    )
      .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: AIModel[] = [];
          for (const i of result.result.ai_models) {
            data.push({
              key: i.ID,
              id: i.ID,
              name: i.name,
              description: i.description,
              model_type: i.model_type,
            });
          }

          pagination.total = result.result.total;
          console.log('set pagination', pagination);
          setPagination(pagination);
          console.log('set table data', data);
          setTableData(data);
        },
        (error) => {
          console.log(error);
        },
      );
  }

  const handleOk = () => {
    console.log('editModel', editModel);
    if (editModel.id > 0) {
      axios
        .put(`/api/v1/ai_model`, editModel)
        .then((resp) => {
          console.log('resp', resp);
          if (resp.status === 200) {
            notification.success({ message: '成功!' });
          }
        })
        .then(() => loadData());
    } else {
      axios
        .post(`/api/v1/ai_model`, editModel)
        .then((resp) => {
          console.log('resp', resp);
          if (resp.status === 200) {
            notification.success({ message: '成功!' });
          }
        })
        .then(() => loadData());
    }

    setIsModalOpen(false);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };

  useEffect(() => {
    loadData();
  }, []);

  return (
    <PageContainer>
      <Space direction="vertical" size="middle" style={{ display: 'flex' }}>
        <ProCard ghost gutter={8}>
          <ProCard
            style={{ minHeight: '90vh', height: '100px', overflowY: 'scroll' }}
            colSpan={24}
            bordered
          >
            <Table
              pagination={pagination}
              columns={columns}
              dataSource={tableData}
            />
          </ProCard>
          <Modal
            title="Edit AI Model"
            open={isModalOpen}
            onOk={handleOk}
            onCancel={handleCancel}
          >
            <Form
              name="basic"
              labelCol={{ span: 8 }}
              wrapperCol={{ span: 16 }}
              initialValues={{
                remember: true,
                name: editModel?.name,
                description: editModel?.description,
                model_type: editModel?.model_type,
              }}
              autoComplete="off"
            >
              <Form.Item
                label="Name"
                name="name"
                rules={[{ required: true, message: 'Model name is required' }]}
              >
                <Input
                  onChange={(event: Event) => {
                    const model = editModel;
                    model.name = event.target.value;
                    setEditModel(model);
                  }}
                />
              </Form.Item>
              <Form.Item
                label="Description"
                name="description"
                rules={[{ required: true, message: 'Description is required' }]}
              >
                <Input
                  onChange={(event: Event) => {
                    const model = editModel;
                    model.description = event.target.value;
                    setEditModel(model);
                  }}
                />
              </Form.Item>
              <Form.Item
                label="Model Type"
                name="model_type"
                rules={[{ required: true, message: 'Model Type is required' }]}
              >
                <Input
                  disabled={editModel?.id > 0 ? true : false}
                  onChange={(event: Event) => {
                    const model = editModel;
                    model.model_type = event.target.value;
                    setEditModel(model);
                  }}
                />
              </Form.Item>
            </Form>
          </Modal>
        </ProCard>
      </Space>
    </PageContainer>
  );
};
