import { memo, useCallback, useEffect, useMemo, useState } from 'react'
import { Button } from 'antd'

import { useWell } from '@asb/context'
import { UserView } from '@components/views'
import DownloadLink from '@components/DownloadLink'
import LoaderPortal from '@components/LoaderPortal'
import { invokeWebApiWrapperAsync } from '@components/factory'
import { makeColumn, makeDateColumn, makeTextColumn, Table } from '@components/Table'
import { delay, wrapPrivateComponent } from '@utils'

import WellCaseEditor from './WellCaseEditor'
import { HistoryTable } from './HistoryTable'

const columns = [
    makeTextColumn('Категория', 'caption'),
    makeColumn('Файл', 'file', {
        render: (file) => file ? (
            <DownloadLink file={file} />
        ) : (
            <span>Файл не загружен</span>
        ),
    }),
    makeDateColumn('Дата загрузки', 'uploadDate'),
    makeColumn('Ответственные', 'responsible', {
        render: (responsible) => responsible.map((user) => (
            <UserView user={user} />
        )),
    }),
]

const WellCase = memo(() => {
    const [isLoading, setIsLoading] = useState(false)
    const [categories, setCategories] = useState([])
    const [canEdit, setCanEdit] = useState(false)
    const [showEdit, setShowEdit] = useState(false)
    const [users, setUsers] = useState([])

    const [well] = useWell()

    const updateTable = useCallback(() => {
        invokeWebApiWrapperAsync(
            async () => {
                await delay(1000)
                const categories = [{ responsible: [{}] }]

                setCanEdit(true)
                const showingCategories = categories.filter((cat) => cat.responsible && cat.responsible?.length > 0)
                setCategories(showingCategories)
            },
            setIsLoading,
            'Не удалось загрузить список категорий',
        )
    }, [well])

    const onEditClose = useCallback((changed = false) => {
        setShowEdit(false)
        if (changed) updateTable()
    }, [updateTable])

    const expandable = useMemo(() => ({
        expandedRowRender: (category) => (
            <HistoryTable users={users} category={category} />
        )
    }), [users])

    useEffect(() => updateTable(), [updateTable])

    return (
        <>
            <LoaderPortal show={isLoading}>
                {canEdit && (
                    <Button onClick={() => setShowEdit(true)}>Редактировать</Button>
                )}
                <Table
                    bordered
                    size={'small'}
                    dataSource={categories}
                    columns={columns}
                    expandable={expandable}
                />
            </LoaderPortal>
            <WellCaseEditor users={users} show={showEdit} onClose={onEditClose} />
        </>
    )
})

export default wrapPrivateComponent(WellCase, {
    title: 'Дело скважины',
    route: 'well_case',
    requirements: [],
})
