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 { CRMError } from 'Components/Common/Error';
import Output from 'Components/Output';
import Head from 'next/head';
import { getOwnerData, useInsuranceData, useMainData } from 'process/init/get-data';
import { useReactions } from 'process/init/inject-reactions/hooks';
import styled from 'styled-components';
import { Box } from 'ui/grid';
import { min } from 'ui/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({ error }) {
  useMainData();
  useInsuranceData();
  useReactions();

  if (error) return <CRMError />;

  return (
    <Grid>
      <Head>
        <title>Лизинговый калькулятор - Эволюция</title>
      </Head>
      <Calculation.Form />
      <Calculation.Settings />
      <Output />
    </Grid>
  );
}
/** @type {import('next').GetServerSideProps} */
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();
  try {
    const { data } = await getOwnerData(apolloClient, user);

    return {
      props: {
        calculation: {
          options: data,
        },
        initialApolloState: apolloClient.cache.extract(),
        initialQueryState: dehydrate(queryClient),
      },
    };
  } catch (error) {
    return {
      props: {
        error: JSON.stringify(error),
      },
    };
  }
};

export default Home;
