import initializeApollo from '@/apollo/client';
import * as Calculation from '@/Components/Calculation';
import { Error } from '@/Components/Common/Error';
import { Tabs } from '@/Components/Layout/Navigation';
import { screens } from '@/config/ui';
import { NavigationContext } from '@/context/navigation';
import * as hooks from '@/process/hooks';
import { getPageTitle } from '@/utils/page';
import { makeGetUserType } from '@/utils/user';
import { dehydrate, QueryClient } from '@tanstack/react-query';
import dynamic from 'next/dynamic';
import Head from 'next/head';
import { useContext, useEffect } from 'react';

const MediaQuery = dynamic(() => import('react-responsive'), {
  ssr: false,
});

const tabs = [
  {
    Component: () => <Calculation.Settings />,
    key: 'settings',
    title: 'Расчет',
  },
  {
    Component: () => <Calculation.Form prune={['unlimited']} />,
    key: 'form',
    title: 'Параметры',
  },

  {
    Component: () => <Calculation.Output />,
    key: 'output',
    title: 'Результаты',
  },
];

function Content() {
  hooks.useSentryScope();
  hooks.useMainData();
  hooks.useInsuranceData();
  hooks.useReactions();

  const { setCurrentTab, setTabsList } = useContext(NavigationContext);

  useEffect(() => {
    setTabsList(tabs);
    setCurrentTab('settings');
  }, [setCurrentTab, setTabsList]);

  return (
    <>
      <Head>
        <title>{getPageTitle()}</title>
      </Head>
      <MediaQuery maxWidth={screens.laptop}>
        {(match) => {
          if (match) return <Tabs tabs={tabs} />;

          return (
            <Calculation.Layout>
              <Calculation.Form prune={['unlimited']} />
              <Calculation.Settings />
              <Calculation.Output />
            </Calculation.Layout>
          );
        }}
      </MediaQuery>
    </>
  );
}

export default function Page(props) {
  if (props.statusCode !== 200) return <Error {...props} />;

  return <Content />;
}

/** @type {import('next').GetServerSideProps} */
export async function getServerSideProps({ req }) {
  const { cookie = '' } = req.headers;

  const queryClient = new QueryClient();
  const apolloClient = initializeApollo(null, req.headers);
  const getUserType = makeGetUserType({ apolloClient, queryClient });

  try {
    const user = await getUserType({ cookie });

    if (!user.default) {
      return {
        props: {
          initialQueryState: dehydrate(queryClient),
          statusCode: 403,
        },
      };
    }

    return {
      props: {
        calculation: {},
        initialApolloState: apolloClient.cache.extract(),
        initialQueryState: dehydrate(queryClient),
        statusCode: 200,
        user,
      },
    };
  } catch (error) {
    return {
      props: {
        error: JSON.stringify(error),
        initialQueryState: dehydrate(queryClient),
        statusCode: 500,
      },
    };
  }
}
