import moment from 'moment'
import { Input } from 'antd'
import { useState, useEffect } from 'react'

import {
  EditableTable,
  DatePickerWrapper,
  makeColumn,
  makeDateSorter,
  makeNumericColumnOptions,
  makeSelectColumn,
  makeActionHandler,
} from '../../components/Table'
import LoaderPortal from '../../components/LoaderPortal'
import { invokeWebApiWrapperAsync } from '../../components/factory'
import { WellOperationService} from '../../services/api'
import { formatDate } from '../../utils'

const { TextArea } = Input

const basePageSize = 160

const defaultColumns = [
  makeSelectColumn('Конструкция секции', 'idWellSectionType', [], undefined, {
    editable: true,
    width: 160,
    formItemRules: [({ getFieldValue }) => ({
      validator(_, value) {
        if (value?.length > 0)
          return Promise.resolve()
        return Promise.reject('Это обязательное поле!')
      }
    })],
  }),
  makeSelectColumn('Операция', 'idCategory', [], undefined, { editable: true, width: 200 }),
  makeColumn('Доп. инфо', 'categoryInfo', { editable: true, width: 300, input: <TextArea/> }),
  makeColumn('Глубина забоя на начало, м', 'depthStart', makeNumericColumnOptions(2, 'depthStart')),
  makeColumn('Глубина забоя при завершении, м', 'depthEnd', makeNumericColumnOptions(2, 'depthEnd')),
  makeColumn('Время начала', 'dateStart', {
    editable: true,
    width: 200,
    input: <DatePickerWrapper/>,
    initialValue: moment().format(),
    sorter: makeDateSorter('dateStart'),
    render: (_, record) => (
      <div className={'text-align-r-container'}>
        <span>{formatDate(record.dateStart)}</span>
      </div>
    )
  }),
  makeColumn('Часы', 'durationHours', makeNumericColumnOptions(2, 'durationHours')),
  makeColumn('Комментарий', 'comment', { editable: true, input: <TextArea/> }),
]

export const WellOperationsEditor = ({idWell, idType}) => {
  const [pageNumAndPageSize, setPageNumAndPageSize] = useState({current:1, pageSize:basePageSize})
  const [paginationTotal, setPaginationTotal] = useState(0)
  const [operations, setOperations] = useState([])
  const [showLoader, setShowLoader] = useState(false)
  const [columns, setColumns] = useState(defaultColumns)

  useEffect(() => invokeWebApiWrapperAsync(
    async () => {
      let categories = await WellOperationService.getCategories(idWell) ?? []
      categories = categories.map((item) => ({ value: item.id, label: item.name }))

      let sectionTypes = await WellOperationService.getSectionTypes(idWell) ?? []
      sectionTypes = Object.keys(sectionTypes).map((key) => ({ value: parseInt(key), label: sectionTypes[key] }))

      setColumns(preColumns => {
        preColumns[0] = makeSelectColumn('Конструкция секции', 'idWellSectionType', sectionTypes, undefined, { editable: true, width: 160 })
        preColumns[1] = makeSelectColumn('Операция', 'idCategory', categories, undefined, { editable: true, width: 200 })
        return preColumns
      })
    },
    setShowLoader,
    'Не удалось загрузить список операций по скважине'
  ), [idWell])

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

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

  const handlerProps = {
    service: WellOperationService,
    setLoader: setShowLoader,
    errorMsg: `Не удалось выполнить операцию`,
    onComplete: updateOperations,
    idWell
  }

  const recordParser = (record) => ({
    ...record,
    idType,
    wellDepth: +record.wellDepth,
    durationHours: +record.durationHours
  })

  return (
    <LoaderPortal show={showLoader}>
      <EditableTable
        size={'small'}
        bordered
        columns={columns}
        dataSource={operations}
        onRowAdd={makeActionHandler('insertRange', handlerProps, recordParser)}
        onRowEdit={makeActionHandler('update', handlerProps, recordParser)}
        onRowDelete={makeActionHandler('delete', handlerProps)}
        pagination={{
          current: pageNumAndPageSize.current,
          pageSize: pageNumAndPageSize.pageSize,
          showSizeChanger: false,
          total: paginationTotal,
          onChange: (page, pageSize) => setPageNumAndPageSize({ current: page, pageSize })
        }}
      />
    </LoaderPortal>
  )
}
