import { useState, useEffect } from 'react'

import {
    makeColumn,
    makeNumericAvgRange,
    makeNumericStartEnd
} from '../../components/Table'
import LoaderPortal from '../../components/LoaderPortal'
import { invokeWebApiWrapperAsync } from '../../components/factory'
import { EditableTable, SelectFromDictionary } from '../../components/Table'
import { DrillingParamsService } from '../../services/api'
import { dictionarySectionType, getByKeyOrReturnKey } from './dictionary'

const basePageSize = 160;


export const WellOpeationsModes = ({idWell}) => {
    const [pageNumAndPageSize, setPageNumAndPageSize] = useState({current:1, pageSize:basePageSize})
    const [paginationTotal, setPaginationTotal] = useState(0)
    const [params, setParams] = useState([])
    const [showLoader, setShowLoader] = useState(false)

    const updatePrograms = () => invokeWebApiWrapperAsync(
        async () => {
            const skip = ((pageNumAndPageSize.current - 1) * pageNumAndPageSize.pageSize) || 0
            const take = pageNumAndPageSize.pageSize
            const paginatedParams = await DrillingParamsService.getParams(idWell, skip, take)
            const params = paginatedParams?.items ?? []
            setParams(params)
            const total = paginatedParams.count?? paginatedParams.items?.length ?? 0
            setPaginationTotal(total)
        },
        setShowLoader,
        'Не удалось загрузить список режимов бурения скважины'
    )

    useEffect(updatePrograms, [idWell, pageNumAndPageSize])

    const columns = [
        makeColumn('Конструкция секции','id_wellsection_type', {
            editable:true,
            input:<SelectFromDictionary dictionary={dictionarySectionType}/>,
            width:160,
            render:(_, record)=>getByKeyOrReturnKey(dictionarySectionType, record.idWellSectionType)
        }),
        makeNumericStartEnd('Глубина', 'depth', true),
        makeNumericAvgRange('Нагрузка', 'axial_load', true),
        makeNumericAvgRange('Давление', 'pressure', true),
        makeNumericAvgRange('Момент на ВПС', 'rotor_torque', true),
        makeNumericAvgRange('Обороты на ВПС', 'rotor_speed', true),
        makeNumericAvgRange('Расход', 'flow', true)
    ]

    const onAdd = async (param) => {
        if (!param.id) return
        // TODO: Add row
        await DrillingParamsService.insertRange(idWell, [param])
        updatePrograms()
    }

    const onEdit = async (param) => {
        if (!param.id) return
        // TODO: Edit row
        await DrillingParamsService.update(idWell, param.id, param)
        updatePrograms()
    }

    const onDelete = async (param) => {
        if (!param.id) return
        await DrillingParamsService.delete(idWell, param.id)
        updatePrograms()
    }

    return (
        <LoaderPortal show={showLoader}>
            <EditableTable
                size={'small'}
                bordered
                columns={columns}
                dataSource={params}
                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})
                }}
            />
        </LoaderPortal>
    )
}
