import { useState, useEffect } from 'react'
import { Input, DatePicker } from 'antd'
import { EditableTable } from "../components/EditableTable"
import LoaderPortal from '../components/LoaderPortal'
import { makeColumn, RegExpIsFloat, invokeWebApiWrapperAsync } from '../components/factory'
import { WellOperationService} from '../services/api'

const numericColumnOptions = {
  editable: true,
  initialValue: 0,
  formItemRules: [
    {
      required: true,
      message: `Введите число`,
      pattern: RegExpIsFloat,
    },
  ],
};

const TypeSelector = <Input list={'sectionTypeList'}/>

const DataListSectionTypes = <datalist id="sectionTypeList">
  <option value="Пилотный ствол">Пилотный ствол</option>
  <option value="Направление">Направление</option>
  <option value="Кондуктор">Кондуктор</option>
  <option value="Эксплуатационная колонна">Эксплуатационная колонна</option>
  <option value="Транспортный ствол">Транспортный ствол</option>
  <option value="Хвостовик">Хвостовик</option>
</datalist>

const columns = [
  makeColumn('Конструкция секции','wellSectionTypeName', {editable:true, input:TypeSelector}),
  makeColumn('Операция','categoryName', {editable:true, input:TypeSelector}),
  makeColumn('Доп. инфо','info', {editable:true}),
  makeColumn('Глубина забоя','wellDepth', numericColumnOptions),
  makeColumn('Время начала','startDate', {editable:true, input:<DatePicker/>}),
  makeColumn('Продолжительность','durationHours', numericColumnOptions),
  makeColumn('Комментарий','comment', {editable:true}),
]

const basePageSize = 32;

export default function WellOperationsEditor({idWell, type}){
  const [pageNumAndPageSize, setPageNumAndPageSize] = useState({current:1, pageSize:basePageSize})
  const [paginationTotal, setPaginationTotal] = useState(0)
  const [operations, setOperations] = useState([])
  const [showLoader, setShowLoader] = useState(false)

  const updateOperations = () => invokeWebApiWrapperAsync(
    async () => {
      const skip = ((pageNumAndPageSize.current - 1) * pageNumAndPageSize.pageSize) || 0
      const take = pageNumAndPageSize.pageSize
      const paginatedOperations = await WellOperationService.getOperations(idWell, type, undefined, undefined, undefined, undefined, skip, take )
      setOperations(paginatedOperations?.items??[])
      const total = paginatedOperations.count?? paginatedOperations.items?.length ?? 0      
      setPaginationTotal(total)
    },
    setShowLoader,
    'Не удалось загрузить список операций по скважине'
  )

  useEffect(updateOperations, [idWell, type, pageNumAndPageSize])

  const onAdd = (newOperation) => {

  }

  const onEdit= (newOperation) => {

  }

  const onDelete= (newOperation) => {

  }

  return <LoaderPortal show={showLoader}>
    <EditableTable
      columns={columns}
      dataSource={operations}
      onRowAdd={onAdd}
      onRowEdit={onEdit}
      onRowDelete={onDelete}
      pagination={{
        current: pageNumAndPageSize.current,
        pageSize: pageNumAndPageSize.pageSize,
        showSizeChanger: false,
        total: paginationTotal,
        onChange: (page, pageSize) => setPageNumAndPageSize({current: page, pageSize: pageSize})
      }}
      />
    {DataListSectionTypes}
  </LoaderPortal> 
}