import React from 'react';
import { Timeline, Spin } from 'antd';

import { dispatch } from '../../../../model'
import Update from './update-rule-catalog'

const FC = ({ item }) => {
  const [versions, setVersions] = React.useState()
  const [loading, setLoading] = React.useState(false)
  const [updateParams, setUpdateParams] = React.useState({
    visible: false,
    type: undefined,
    item: undefined,
  });

  React.useEffect(() => {
    if (item?.id) {
      getVersions()
    }
    
    //eslint-disable-next-line react-hooks/exhaustive-deps
  }, [item])

  const getVersions = () => {
    setLoading(true);
    dispatch({
      type: 'datamodel.getRuleCatalogVersionList',
      payload: {
        catalogId: item?.id,
      },
      callback: data => {
        setLoading(false)
        setVersions(data)
      },
      error: () => {
        setLoading(false);
      }
    })
  }

  return (
    <React.Fragment>
      <Spin spinning={loading}>
        <Timeline style={{ padding: 24 }}>
        {
          (versions??[]).map((version, index) => {
            return <Timeline.Item key={index} >
              <div>
                <a
                  onClick={() => {
                    setUpdateParams({
                      visible: true,
                      type: 'detail',
                      item: version
                    })
                  }}
                >
                  {version.name}
                </a>
                <div className='mt-2'>
                {`${version.ownerName} ${new Date(version.createdTs).toLocaleString()}`}
                </div>
              </div>
            </Timeline.Item>
          })
        }
        </Timeline>
      </Spin>
      <Update 
        {...updateParams}
        onCancel={() => {
          setUpdateParams({
            visible: false,
            type: undefined,
            item: undefined,
          })
        }}
      />
    </React.Fragment>
  );
}

export default FC