import { Alert, Snackbar, Typography } from '@mui/material';
import { Box } from '@mui/system';
import { useSession } from 'next-auth/react';
import { useState } from 'react';
import { updateUser } from '../../requests/user/userUpdateRequest';
import { useUserUpdate } from '../../store/user-context';
import OrderCard from '../cards/order-card/OrderCard';
import ShippingDetailsForm from '../forms/shipping-details/ShippingDetailsForm';
import StepTitle from '../layout/steps-title/StepTitle';

const ProfileContent = ({ orders }) => {
  const { data: session } = useSession();
  const { updateUserInfo } = useUserUpdate();
  const [enableBtn, setEnableBtn] = useState(true);
  const [open, setOpen] = useState(false);

  const updateUserHandler = async (values) => {
    try {
      setEnableBtn(false);
      updateUserInfo(values);
      await updateUser(values, session.user._id);
      setOpen(true);
      setTimeout(() => {
        setEnableBtn(true);
      }, 5000);
    } catch (error) {
      console.log(error);
      setTimeout(() => {
        setEnableBtn(true);
      }, 3000);
    }
  };

  const handleCloseNotification = () => {
    setOpen(false);
  };

  const mapOrdersToDom = () =>
    orders.slice(-4).map((order, i) => (
      <OrderCard
        key={i}
        data={{
          date: order.time.split('T')[0],
          name: order.shippingAddress.fullName,
          totalPrice: order.totalPrice,
        }}
      ></OrderCard>
    ));

  return (
    <Box sx={{ py: 10, height: '100%', width: '100%' }}>
      <StepTitle title="Items in Your Cart" />
      <Snackbar
        anchorOrigin={{ vertical: 'top', horizontal: 'center' }}
        open={open}
        autoHideDuration={3000}
        onClose={handleCloseNotification}
      >
        <Alert
          onClose={handleCloseNotification}
          severity="success"
          sx={{ width: '100%', backgroundColor: 'green', color: 'white' }}
        >
          User profile updated!
        </Alert>
      </Snackbar>

      <Box
        sx={{
          display: 'flex',
          flexDirection: { xs: 'column', md: 'row' },
          mr: { xs: 2, md: 12 },
          ml: { xs: 2, md: 12 },
        }}
      >
        <Box
          sx={{
            width: { xs: '100%', md: '100%' },
            mt: 2,
            mr: { md: 2 },
            mb: { xs: 6 },
          }}
        >
          <Typography sx={{ fontSize: 20, mb: 3 }}>
            Save details for later
          </Typography>
          <ShippingDetailsForm
            submitHandler={updateUserHandler}
            enableBtn={enableBtn}
          ></ShippingDetailsForm>
        </Box>

        <Box
          sx={{
            mt: 2,
            maxWidth: { sm: '100%', lg: '10%' },
            minWidth: { md: '40%' },
          }}
        >
          <Typography sx={{ fontSize: 20, mb: 3 }}>Previous Orders</Typography>
          {mapOrdersToDom()}
        </Box>
      </Box>
    </Box>
  );
};

export default ProfileContent;
