/* eslint-disable object-curly-newline */
import { useApolloClient } from '@apollo/client';
import { dehydrate, QueryClient } from '@tanstack/react-query';
import { getUser } from 'api/user/query';
import initializeApollo from 'apollo/client';
import * as Calculation from 'Components/Calculation';
import Output from 'Components/Output';
import Head from 'next/head';
import getData, { getOwnerData } from 'process/init/get-data';
import injectDefaultReactions from 'process/init/inject-reactions/default';
import { useEffect } from 'react';
import { useStore } from 'stores/hooks';
import styled from 'styled-components';
import { Box } from 'UIKit/grid';
import { min } from 'UIKit/mq';

const Grid = styled(Box)`
  display: flex;
  flex-direction: column;
  gap: 10px;

  ${min('laptop')} {
    display: grid;
    align-items: flex-start;
    grid-template-columns: 2fr 1fr;
  }

  ${min('laptop-hd')} {
    grid-template-columns: 2fr 1fr 1.5fr;
  }

  ${min('desktop')} {
    margin: 8px 5%;
  }

  ${min('desktop-xl')} {
    margin: 8px 10%;
  }
`;

function Home() {
  const store = useStore();
  const apolloClient = useApolloClient();

  useEffect(() => {
    getData(apolloClient, store);
    injectDefaultReactions(store, apolloClient);
  }, []);

  return (
    <Grid>
      <Head>
        <title>Лизинговый калькулятор - Эволюция</title>
      </Head>
      <Calculation.Form />
      <Calculation.Settings />
      <Output />
    </Grid>
  );
}

export const getServerSideProps = async ({ req }) => {
  const { cookie = '' } = req.headers;
  // prettier-ignore
  const queryGetUser = () => getUser({
    headers: {
      cookie,
    },
  });

  const queryClient = new QueryClient();
  const user = await queryClient.fetchQuery(['user'], queryGetUser);

  const apolloClient = initializeApollo();
  const { options: ownerOptions } = await getOwnerData(apolloClient, user);

  return {
    props: {
      calculation: {
        options: ownerOptions,
      },
      initialApolloState: apolloClient.cache.extract(),
      initialQueryState: dehydrate(queryClient),
    },
  };
};

export default Home;
