import type { NextPage } from 'next'
import Head from 'next/head'
import { GroupProvider, useGroups } from '../../components/contexts/GroupProvider'
import { useFactories } from '../../src/hooks/useFactories'
import { ProducingGraph } from '../../components/shared/ProducingGraph/ProducingGraph'
import { useEffect, useMemo } from 'react'
import { calculateInputs } from '../../src/calculateInputs'
import {
  NodeOverview,
  OverviewGraphNode
} from '../../components/visualize/NodeOverview/NodeOverview'
import { fixedEncodeURIComponent } from '../../src/utils'
import { ScrollContainer } from '../../components/shared/ScrollContainer/ScrollContainer'
import { getServerSidePropsGroupProvider, PropsGroupProvider } from '../../src/getServerSideProps'

const Page: NextPage<PropsGroupProvider> = ({ id, ...initial }) => {
  const { exportedFactories, baseFactories, groups } = useGroups()
  const { findFactory } = useFactories()

  useEffect(() => {
    document.body.classList.add('scroll')
    return () => document.body.classList.remove('scroll')
  }, [])

  const producingNodes: OverviewGraphNode[] = useMemo(() => {
    return Object.values(groups).map(group => ({
      inputs: calculateInputs(
        [...group.exports, ...group.malls],
        baseFactories,
        exportedFactories,
        findFactory
      )[0],
      outputs: group.exports,
      name: group.name,
      icons: [...group.exports, ...group.malls],
      linkOut: `./visualize/${fixedEncodeURIComponent(group.name)}`
    }))
  }, [baseFactories, exportedFactories, findFactory, groups])

  return (
    <GroupProvider id={id} initial={initial}>
      <Head>
        <title>Factorio Microservices</title>
        <meta name='description' content='Create Factorio microservices' />
        <link rel='icon' href='/public/favicon.ico' />
      </Head>
      <main>
        <ScrollContainer>
          <h1>Factorio Microservices</h1>
          <ProducingGraph nodes={producingNodes} inputs={baseFactories} childType={NodeOverview} />
        </ScrollContainer>
      </main>
    </GroupProvider>
  )
}

export const getServerSideProps = getServerSidePropsGroupProvider

export default Page
