import { Descriptions } from 'antd'
import { memo, useEffect, useState } from 'react'

import { makeNumericRender } from '@components/Table'
import { invokeWebApiWrapperAsync } from '@components/factory'
import { formatDate, fractionalSum } from '@utils/datetime'

import '@styles/tvd.less'

const { Item } = Descriptions

const calcEndDate = (saubData) => {
    if (!Array.isArray(saubData) || saubData.length <= 0) return [null, null]
    const lastElm = saubData.at(-1)
    return [saubData[0]?.date, fractionalSum(lastElm?.date, lastElm?.nptHours, 'hour')]
}

const numericRender = makeNumericRender(2)
const printDate = (date) => formatDate(date) ?? '-'

export const AdditionalTables = memo(({ operations, xLabel, setIsLoading }) => {
    const [additionalData, setAdditionalData] = useState({})

    useEffect(() => invokeWebApiWrapperAsync(
        async () => {
            const [factStartDate, factEndDate] = calcEndDate(operations.fact)
            const [planStartDate, planEndDate] = calcEndDate(operations.plan)
            const [predictStartDate, predictEndDate] = calcEndDate(operations.predict)

            const last = predictEndDate ?? factEndDate
            setAdditionalData({
                lag: (+new Date(last) - +new Date(planEndDate)) / 86400_000,
                endDate: last,
                factStartDate,
                factEndDate,
                planStartDate,
                planEndDate,
                predictStartDate,
                predictEndDate,
            })
        },
        setIsLoading,
        'Не удалось высчитать дополнительные данные'
    ), [operations, setIsLoading])

    return (
        <>
            <div className={'tvd-tr-table'}>
                <Descriptions bordered column={1} size={'small'} style={{ backgroundColor: 'white' }}>
                    <Item label={'Дата завершения'}>{printDate(additionalData.endDate)}</Item>
                    <Item label={'Отставание (сут)'}>{numericRender(additionalData.lag)}</Item>
                </Descriptions>
            </div>
            <div className={'tvd-bl-table'} style={{ bottom: xLabel === 'day' ? '35px' : '85px' }}>
                <Descriptions bordered column={1} size={'small'} style={{ backgroundColor: 'white' }}>
                    <Item label={'Отставание (сут)'}>{numericRender(additionalData.lag)}</Item>
                    <Item label={'Начало цикла (план)'}>{printDate(additionalData.planStartDate)}</Item>
                    <Item label={'Начало цикла (факт)'}>{printDate(additionalData.factStartDate)}</Item>
                    <Item label={'Окончание цикла (план)'}>{printDate(additionalData.planEndDate)}</Item>
                    <Item label={'Окончание цикла (факт)'}>{printDate(additionalData.factEndDate)}</Item>
                </Descriptions>
            </div>
        </>
    )
})

export default AdditionalTables
