import { Grid, Typography } from '@mui/material';
import { Box } from '@mui/system';
import { useSession } from 'next-auth/react';
import { useRouter } from 'next/router';
import { setCookie } from 'nookies';
import { useStore } from '../../store/cart-context';
import { useCheckoutDataUpdate } from '../../store/checkout-context';
import DataCard from '../cards/data-card/DataCard';
import ShippingDetailsForm from '../forms/shipping-details/ShippingDetailsForm';
import StepTitle from '../layout/steps-title/StepTitle';

const CheckoutContent = () => {
  const { cartStorage } = useStore();
  const { addCheckoutValue } = useCheckoutDataUpdate();

  const { data: session } = useSession();
  const router = useRouter();

  const submitHandler = (formValues) => {
    addCheckoutValue(
      cartStorage,
      { ...formValues, email: session.user.email },
      session.user._id
    );
    setCookie(null, 'shipping-session', 'active', {
      maxAge: 3600,
      expires: new Date(Date.now() + 3600),
      path: '/',
    });
    router.push('/shipping');
  };

  const mapProductsToDom = () => {
    return cartStorage?.map((entry, i) => (
      <DataCard
        key={i}
        data={entry.product}
        quantity={entry.quantity}
      ></DataCard>
    ));
  };

  return (
    <Grid container spacing={2} sx={{ py: 10, height: '100%', width: '100%' }}>
      <StepTitle
        title="Items in Your Cart"
        breadcrumbsArray={['Cart', 'Checkout']}
      />
      <Grid item xs={12} sx={{ mt: 1 }}>
        <Typography sx={{ pl: 12, fontSize: 20 }}>
          The following fields will be used as the shipping details for your
          order
        </Typography>
      </Grid>
      <Grid item xs={8}>
        <ShippingDetailsForm
          backBtn={true}
          isCheckout={true}
          submitHandler={submitHandler}
        ></ShippingDetailsForm>
      </Grid>
      <Grid item xs={4}>
        <Box sx={{ width: '80%', mt: 2 }}>{mapProductsToDom()}</Box>
      </Grid>
    </Grid>
  );
};

export default CheckoutContent;
