import { useState, useEffect } from 'react'
import { Table, Button, Modal } from 'antd'
import { HourglassOutlined } from '@ant-design/icons'
import LoaderPortal from '../../components/LoaderPortal'
import { invokeWebApiWrapperAsync } from '../../components/factory'
import { MeasureService } from '../../services/api'
import { Editor } from './Editor'

export const MeasureTable = ({idWell, idCategory, title, columns}) => {
  const [showLoader, setShowLoader] = useState(false)
  const [showEditor, setShowEditor] = useState(false)
  const [lastData, setLastData] = useState({})

  const update = ()=>invokeWebApiWrapperAsync(async()=>{
    const data = await MeasureService.getLast(idWell, idCategory)
    setLastData(data)
  }
  , setShowLoader
  , "не удалось загрузить")

  useEffect(update, [idWell, idCategory])

  const timestamp = lastData ? new Date(lastData?.timestamp).toLocaleString() : '-'

  return <LoaderPortal show={showLoader}>
    <h3>{title}</h3>
    <span>Дата: {timestamp}</span>
    &nbsp;
    <Button 
      onClick={() => setShowEditor(true)}
      icon={<HourglassOutlined/>}>История</Button>  
    <Table
      style={{marginTop:16}}
      bordered
      dataSource = {[lastData?.data]}
      columns = {columns}
      scroll={{ x: 400, y: 600 }}/>
    <Modal
        title={title}
        centered
        visible={showEditor}
        onOk={() => setShowEditor(false)}
        onCancel={() => setShowEditor(false)}
        width="95%"
        footer={null}
        >
      <Editor
        idWell={idWell}
        idCategory={idCategory} 
        columns = {columns}
        onUpdate={update}/>
    </Modal>
  </LoaderPortal>
}