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 { useDefaultReactions } from '@/config/process';
import * as init from '@/process/init';
import { min } from '@/styles/mq';
import { dehydrate, QueryClient } from '@tanstack/react-query';
import Head from 'next/head';
import styled from 'styled-components';
import { Box } from 'ui/grid';

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 }) {
  init.useMainData();
  init.useInsuranceData();
  useDefaultReactions();

  if (error) return <CRMError error={error} />;

  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;
  const queryGetUser = () =>
    getUser({
      headers: {
        cookie,
      },
    });

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

  const apolloClient = initializeApollo();

  try {
    const { values, options } = await init.getInitialData(apolloClient, user);

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

export default Home;
