import ShopfrontLayout from 'src/@core/layouts/ShopfrontLayout';
import { Box, Button, Stack, Typography } from '@mui/material';
import { useContext, useEffect, useState } from 'react';
import { CartContext } from 'src/contexts/cart';
import Link from 'next/link';
import fetchProduct from 'src/api/fetchProduct';
import Loading from 'src/components/Loading';
import checkoutCart from 'src/api/checkoutCart';
import { LoadingButton } from '@mui/lab';
import { useRouter } from 'next/router';
import ChevronLeft from '@mui/icons-material/ChevronLeft';
import CartItemDetail from 'src/components/CartItemDetail';
import Checkout from 'src/components/Checkout';
import { PayPalScriptProvider } from '@paypal/react-paypal-js';
import CheckSession from 'src/api/checkSession';
import { setup } from 'src/lib/csrf';

const initialOptions = {
  'client-id': 'AQT5-eAKNK7IhAhBGlbHBu_9jBx74ZLCfEioKUWQMXMuMmLcnffmpoUz_z-ewOuKZmpSlDk74UtlH58O',
  currency: 'HKD',
  intent: 'capture',
};

function NoProductInCart() {
  return (
    <>
      <Stack direction="column" height="30vh" justifyContent={'center'} alignItems={'center'} spacing={'3rem'}>
        <Typography variant="h5">No product in cart,</Typography>
        <Typography variant="h5">
          <Link href="/">
            <Button variant={'contained'} size="large" startIcon={<ChevronLeft />}>
              go add some
            </Button>
          </Link>
        </Typography>
      </Stack>
    </>
  );
}

function CartPage() {
  let route = useRouter();

  const { cart, total_price, products, proceedCheckOutCart } = useContext(CartContext);
  let [checking_out, setCheckingOut] = useState(false);

  // let [purchase_units, setPurchaseUnits] = useState([{ amount: { value: total_price } }]);

  const handleCheckoutOnClick = () => {
    const proceedCheckout = async () => {
      try {
        setCheckingOut(true);
        await proceedCheckOutCart();

        route.replace('/shopfront/cart/Thankyou');
      } catch (error) {
        console.error(error);
        alert('error found during checkout');
      }
    };
    proceedCheckout();
  };

  useEffect(() => {
    const check = async () => {
      try {
        let { session } = JSON.parse(localStorage.getItem('session')) || '';

        let data = await CheckSession({ session });
        if (data['status'] != 'OK') {
          return route.replace('/shopfront/login');
        } else {
          // assume 'status' is ok here
          if (data['role'] == 'admin') {
            return route.replace('/admin');
          } else {
            return route.replace('/shopfront/cart');
          }
        }
      } catch (error) {
        console.log(error);
      }
    };

    return check();
  }, []);

  let [refresh_paypal, setRefreshPaypal] = useState(false);

  useEffect(() => {
    setRefreshPaypal(true);
    setTimeout(() => {
      setRefreshPaypal(false);
    }, 1);

    // force regenerate component
  }, [total_price]);

  if (!cart || !products) return <Loading />;
  if (products.length < 1) return <Loading />;

  return (
    <>
      <Stack gap="1rem" width="100%" justifyContent={'center'} alignItems={'center'}>
        {cart.length < 1 ? (
          <NoProductInCart />
        ) : (
          <>
            {cart.map((p, idx) => {
              return (
                <>
                  <CartItemDetail
                    checking_out={checking_out}
                    products={products}
                    key={idx}
                    pid={p.pid}
                    qty={p.quantity}
                  />
                </>
              );
            })}
            <Box sx={{ borderTop: '1px solid rgba(0,0,0,0.2)', width: '50%', padding: '1rem' }} />
            <Box>
              <Box>
                <Typography variant="h6">Total: HKD {total_price.toFixed(2)}</Typography>
                {/*
                <LoadingButton loading={checking_out} onClick={handleCheckoutOnClick} variant={'contained'}>
                  {checking_out ? 'Checking out...' : 'press to Checkout'}
                </LoadingButton>
                */}

                <PayPalScriptProvider options={initialOptions}>
                  <Box sx={{ height: '100px', minWidth: '200px', maxWidth: '300px' }}>
                    {refresh_paypal ? (
                      <>refreshing</>
                    ) : (
                      <>
                        <Checkout />
                      </>
                    )}
                  </Box>
                </PayPalScriptProvider>
              </Box>
            </Box>
          </>
        )}
      </Stack>
    </>
  );
}

CartPage.getLayout = page => <ShopfrontLayout>{page}</ShopfrontLayout>;

export const getServerSideProps = setup(async ({ req, res }) => {
  return { props: {} };
});

export default CartPage;
