import { 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 (
    <Box container spacing={2} sx={{ py: 10, height: '100%', width: '100%' }}>
      <StepTitle
        title="Items in Your Cart"
        breadcrumbsArray={['Cart', 'Checkout']}
      />
      <Box sx={{ ml: { xs: 2, md: 12 }, my: 2 }}>
        <Typography sx={{ fontSize: 20 }}>
          The following fields will be used as the shipping details for your
          order
        </Typography>
      </Box>
      <Box
        sx={{
          display: 'flex',
          flexDirection: { xs: 'column', lg: 'row' },
          mr: { xs: 2, md: 12 },
          ml: { xs: 2, md: 12 },
        }}
      >
        <Box flexGrow={1}>
          <ShippingDetailsForm
            backBtn={true}
            isCheckout={true}
            submitHandler={submitHandler}
          ></ShippingDetailsForm>
        </Box>
        <Box
          sx={{
            ml: { lg: 2 },
            mt: { xs: 5, md: 5, lg: 2 },
            display: 'flex',
            flexDirection: { xs: 'column', sm: 'row', lg: 'column' },
            justifyContent: { sm: 'space-between', md: 'flex-start' },
            flexWrap: 'wrap',
          }}
        >
          {mapProductsToDom()}
        </Box>
      </Box>
    </Box>
  );
};

export default CheckoutContent;
