import { Tag, TreeSelect } from 'antd'
import { memo, useEffect, useState } from 'react'

import { invokeWebApiWrapperAsync } from '@components/factory'
import { hasPermission } from '@utils/permissions'
import { DepositService } from '@api'

export const getTreeData = async () => {
    const deposits = await DepositService.getDeposits()
    const wellsTree = deposits.map((deposit, dIdx) => ({
        title: deposit.caption,
        key: `0-${dIdx}`,
        value: `0-${dIdx}`,
        children: deposit.clusters.map((cluster, cIdx) => ({
            title: cluster.caption,
            key: `0-${dIdx}-${cIdx}`,
            value: `0-${dIdx}-${cIdx}`,
            children: cluster.wells.map(well => ({
                title: well.caption,
                key: well.id,
                value: well.id,
            })),
        })),
    }))

    return wellsTree
}

export const getTreeLabels = (treeData) => {
    const labels = {}
    treeData.forEach((deposit) =>
        deposit?.children?.forEach((cluster) =>
        cluster?.children?.forEach((well) => {
        labels[well.value] = `${deposit.title}.${cluster.title}.${well.title}`
    })))
    return labels
}

export const WellSelector = memo(({ idWell, value, onChange, treeData, treeLabels, ...other }) => {
    const [wellsTree, setWellsTree] = useState([])
    const [wellLabels, setWellLabels] = useState([])

    useEffect(() => invokeWebApiWrapperAsync(
        async () => {
            const wellsTree = treeData ?? await getTreeData()
            const labels = treeLabels ?? getTreeLabels(wellsTree)
            setWellsTree(wellsTree)
            setWellLabels(labels)
        },
        null,
        'Не удалось загрузить список скважин',
        'Получение списка скважин'
    ), [idWell, treeData])

    return (
        <TreeSelect
            multiple
            treeCheckable
            showCheckedStrategy={TreeSelect.SHOW_CHILD}
            treeDefaultExpandAll
            treeData={wellsTree}
            treeLine={{ showLeafIcon: false }}
            size={'middle'}
            style={{ width: '100%' }}
            value={value}
            onChange={onChange}
            placeholder={'Выберите скважины'}
            tagRender={(props) => (
                <Tag {...props}>{wellLabels[props.value] ?? props.label}</Tag>
            )}
            disabled={wellsTree.length <= 0 || !hasPermission('WellOperation.edit')}
            {...other}
        />
    )
})

export default WellSelector
