import { lazy, memo, useCallback, useEffect, useMemo, useState } from 'react'
import { Navigate, Route, Routes, useLocation, useParams } from 'react-router-dom'

import { WellContext, RootPathContext, useRootPath, useLayoutProps, TopRightBlockContext } from '@asb/context'
import { FastRunMenu } from '@components/FastRunMenu'
import { invokeWebApiWrapperAsync } from '@components/factory'
import { makeMenuBreadcrumbItems } from '@components/MenuBreadcrumb'
import { NoAccessComponent, withPermissions } from '@utils'
import { WellService } from '@api'

import { NavigationMenu, menuItems } from './NavigationMenu'

import '@styles/index.css'

const Measure = lazy(() => import('./Measure'))
const Reports = lazy(() => import('./Reports'))
const WellCase = lazy(() => import('./WellCase'))
const Analytics = lazy(() => import('./Analytics'))
const Documents = lazy(() => import('./Documents'))
const Telemetry = lazy(() => import('./Telemetry'))
const WellOperations = lazy(() => import('./WellOperations'))
const DrillingProgram = lazy(() => import('./DrillingProgram'))

const Tvd = lazy(() => import('./WellOperations/Tvd'))
const WellDrillParams = lazy(() => import('./WellOperations/WellDrillParams'))
const DrillProcessFlow = lazy(() => import('./WellOperations/DrillProcessFlow'))
const WellSectionsStat = lazy(() => import('./WellOperations/WellSectionsStat'))
const WellOperationsEditorFact = lazy(() => import('./WellOperations/OperationEditor/Fact'))
const WellOperationsEditorPlan = lazy(() => import('./WellOperations/OperationEditor/Plan'))

const Archive = lazy(() => import('./Telemetry/Archive'))
const Messages = lazy(() => import('./Telemetry/Messages'))
const Operations = lazy(() => import('./Telemetry/Operations'))
const DashboardNNB = lazy(() => import('./Telemetry/DashboardNNB'))
const TelemetryView = lazy(() => import('./Telemetry/TelemetryView'))
const OperationTime = lazy(() => import('./Telemetry/OperationTime'))

const DailyReport = lazy(() => import('./Reports/DailyReport'))
const DiagramReport = lazy(() => import('./Reports/DiagramReport'))

const Statistics = lazy(() => import('./Analytics/Statistics'))
const WellCompositeEditor = lazy(() => import('./Analytics/WellCompositeEditor'))

const Well = memo(() => {
    const { idWell } = useParams()

    const location = useLocation()

    const [well, setWell] = useState({ id: idWell })
    const [topRightBlock, setTopRightBlock] = useState()

    const root = useRootPath()
    const rootPath = useMemo(() => `${root}/well/${idWell}`, [root, idWell])

    const setLayoutProps = useLayoutProps()

    const updateWell = useCallback((data) => invokeWebApiWrapperAsync(
        async () => {
            const newWell = { ...well, ...data }
            await WellService.updateWell(newWell)
            setWell(newWell)
        },
        undefined,
        `Не удалось изменить данные скважины`,
        { actionName: 'Изменение данных скважины', well }
    ), [well])

    useEffect(() => {
        invokeWebApiWrapperAsync(
            async () => {
                const well = await WellService.get(idWell)
                setWell(well ?? { id: idWell })
            },
            undefined,
            'Не удалось получить данные по скважине'
        )
    }, [idWell])

    useEffect(() => setLayoutProps({
        sider: <NavigationMenu idWell={well.id} />,
        breadcrumb: makeMenuBreadcrumbItems(menuItems, location.pathname, /^\/well\/[0-9]+\//),
        topRightBlock: topRightBlock,
    }), [well, location.pathname, setLayoutProps, topRightBlock])

    useEffect(() => setTopRightBlock(undefined), [location])

    return (
        <RootPathContext.Provider value={rootPath}>
            <WellContext.Provider value={[well, updateWell]}>
                <FastRunMenu />
                <TopRightBlockContext.Provider value={setTopRightBlock}>
                    <Routes>
                        <Route index element={<Navigate to={'telemetry'} replace />} />
                        <Route path={'*'} element={<NoAccessComponent />} />

                        <Route path={'telemetry/*'} element={<Telemetry />}>
                            <Route index element={<Navigate to={'telemetry'} replace />} />
                            <Route path={'*'} element={<NoAccessComponent />} />

                            <Route path={'telemetry'} element={<TelemetryView />} />
                            <Route path={'messages'} element={<Messages />} />
                            <Route path={'archive'} element={<Archive />} />
                            <Route path={'dashboard_nnb/*'} element={<DashboardNNB />} />
                            <Route path={'operations'} element={<Operations />} />
                            <Route path={'operation_time'} element={<OperationTime />} />
                        </Route>
                        <Route path={'reports/*'} element={<Reports />}>
                            <Route index element={<Navigate to={'diagram_report'} replace />} />
                            <Route path={'*'} element={<NoAccessComponent />} />

                            <Route path={'diagram_report'} element={<DiagramReport />} />
                            <Route path={'daily_report'} element={<DailyReport />} />
                        </Route>
                        <Route path={'analytics/*'} element={<Analytics />}>
                            <Route index element={<Navigate to={'composite'} replace />} />
                            <Route path={'*'} element={<NoAccessComponent />} />

                            <Route path={'composite/*'} element={<WellCompositeEditor />} />
                            <Route path={'statistics'} element={<Statistics />} />
                        </Route>
                        <Route path={'operations/*'} element={<WellOperations />}>
                            <Route index element={<Navigate to={'tvd'} replace />} />
                            <Route path={'*'} element={<NoAccessComponent />} />

                            <Route path={'tvd'} element={<Tvd />} />
                            <Route path={'sections'} element={<WellSectionsStat />} />
                            <Route path={'plan'} element={<WellOperationsEditorPlan />} />
                            <Route path={'fact'} element={<WellOperationsEditorFact />} />
                            <Route path={'drillProcessFlow'} element={<DrillProcessFlow />} />
                            <Route path={'params'} element={<WellDrillParams />} />
                        </Route>
                        <Route path={'document/*'} element={<Documents />} />
                        <Route path={'measure/*'} element={<Measure />} />
                        <Route path={'drillingProgram'} element={<DrillingProgram />} />
                        <Route path={'well_case'} element={<WellCase />} />
                    </Routes>
                </TopRightBlockContext.Provider>
            </WellContext.Provider>
        </RootPathContext.Provider>
    )
})

export default withPermissions(Well)
