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 { DrillParamsService } from '../../services/api'
import { dictionarySectionType, getByKeyOrReturnKey } from './dictionary'

const basePageSize = 160;


export const WellDrillParams = ({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 DrillParamsService.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'),
        makeNumericAvgRange('Нагрузка', 'axialLoad'),
        makeNumericAvgRange('Давление', 'pressure'),
        makeNumericAvgRange('Момент на ВПС', 'topDriveTorque'),
        makeNumericAvgRange('Обороты на ВПС', 'topDriveSpeed'),
        makeNumericAvgRange('Расход', 'flow')
    ]

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

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

    const onDelete = async (param) => {
        if (!param.id) return
        await DrillParamsService.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>
    )
}
