import { useEffect, useState } from 'react'
import { useHistory, useParams } from 'react-router'
import { invokeWebApiWrapperAsync } from '../../components/factory'
import LoaderPortal from '../../components/LoaderPortal'
import { EditableTable, makeColumn, makeNumericColumn, makeSelectColumn } from '../../components/Table'
import { AdminClusterService, DepositService } from '../../services/api'

export const ClusterController = () => {
    const { page } = useParams()
    const history = useHistory()

    const [deposits, setDeposits] = useState([])
    const [clusters, setClusters] = useState([])
    const [pagination, setPagination] = useState({ current: page ?? 1, pageSize: 20 })
    const [pagintaionTotal, setPagintaionTotal] = useState(0)
    const [showLoader, setShowLoader] = useState(false)

    const clusterColumns = [
        makeSelectColumn('Месторождение', 'idDeposit', deposits, '--', { width: 200, editable: true }),
        makeColumn('Название', 'caption', { width: 200, editable: true }),
        makeColumn('Описание', 'description', { width: 500, editable: true }),
        makeNumericColumn('Широта', 'latitude', null, null, null, 150, { editable: true }),
        makeNumericColumn('Долгота', 'longitude', null, null, null, 150, { editable: true })
    ]

    const updateTable = () => invokeWebApiWrapperAsync(
        async () => {
            history.push(`/admin/cluster/${pagination.current}`)
            const skip = ((pagination.current - 1) * pagination.pageSize) || 0
            const clusters = await AdminClusterService.getPage(skip, pagination.pageSize)
            if (!clusters?.items)
                throw Error(`Не удалось загрузить список кустов`)
            setClusters(clusters.items)
            setPagintaionTotal(clusters.count ?? clusters.items.length ?? 0)
        },
        setShowLoader,
        `Не удалось загрузить список кустов`
    )

    useEffect(() => invokeWebApiWrapperAsync(
        async () => {
            let deposits = await DepositService.getDeposits()
            deposits = deposits?.map((deposit) => ({ value: deposit.id, label: deposit.caption }))
            setDeposits(deposits ?? [])
        },
        setShowLoader,
        `Не удалось загрузить список месторождений`
    ), [])

    useEffect(updateTable, [pagination, history])

    const onAdd = async (cluster) => {
        await AdminClusterService.insert(cluster)
        updateTable()
    }

    const onEdit = async (cluster) => {
        if (!cluster.id) return
        await AdminClusterService.put(cluster.id, cluster)
        updateTable()
    }

    const onDelete = async (cluster) => {
        if (!cluster.id) return
        await AdminClusterService.delete(cluster.id)
        updateTable()
    }

    return (
        <LoaderPortal show={showLoader}>
            <EditableTable
                size={'small'}
                bordered
                columns={clusterColumns}
                dataSource={clusters}
                onRowAdd={onAdd}
                onRowEdit={onEdit}
                onRowDelete={onDelete}
                pagination={{
                    current: pagination.current,
                    pageSize: pagination.pageSize,
                    total: pagintaionTotal,
                    showSizeChanger: false,
                    onChange: (current, pageSize) => setPagination({ current, pageSize })
                }}
            />
        </LoaderPortal>
    )
}
