import { Button, Grid, Tab, Tabs, Typography } from '@mui/material';
import { Box, Container } from '@mui/system';
import { dehydrate, QueryClient } from '@tanstack/react-query';
import Image from 'next/image';
import { useRouter } from 'next/router';
import React, { useState } from 'react';
import Loader from '../../components/loader/Loader';
import TabPanel from '../../components/tab-panel/TabPanel';
import { useFetchSingleProduct } from '../../hooks/useFetchProductData';
import { getProductData } from '../../requests/products/producDataRequest';
import { useStore, useStoreUpdate } from '../../store/cart-context';

const SingleProduct = () => {
  const { addCartValue } = useStoreUpdate();
  const { cartStorage } = useStore();

  const router = useRouter();

  const { customId } = router.query;

  const { data, isLoading } = useFetchSingleProduct(customId);

  // const productCategory = data?.product.category;

  const [value, setValue] = useState(0);

  const addProductToCart = (quantity) => addCartValue(data.product, quantity);
  const inCart = cartStorage?.some(
    (item) => item.product.customID === data?.product.customID
  )
    ? true
    : false;

  const handleChange = (event, newValue) => {
    setValue(newValue);
  };

  function a11yProps(index) {
    return {
      id: `simple-tab-${index}`,
      'aria-controls': `simple-tabpanel-${index}`,
    };
  }

  if (isLoading) {
    return <Loader loading={isLoading} />;
  }

  // const productsToShow = (id) => {
  //   const filtered = shuffle(similarProducts?.productsByCategory)
  //     .filter((product) => product.customID !== id)
  //     .slice(0, 3)
  //     .map((item) => (
  //       <Grid
  //         key={item._id}
  //         item
  //         lg={4}
  //         md={6}
  //         sm={6}
  //         xs={12}
  //         sx={{ mb: '100px' }}
  //       >
  //         <ProductCard product={item} />
  //       </Grid>
  //     ));

  //   return filtered;
  // };

  return (
    <Box
      sx={{
        display: 'flex',
        flexDirection: 'column',
      }}
    >
      <Container>
        <Typography
          fontFamily={'body1.fontFamily'}
          fontSize="32px"
          sx={{ mt: 25, height: '100%', color: 'primary.main' }}
        >
          {data.product.name}
        </Typography>
        <Grid container spacing={2}>
          <Grid item md={6} sm={12}>
            <Image
              src="/images/product-card-image.jpg"
              alt="product"
              width={900}
              height={600}
            />
          </Grid>
          <Grid item xs={12} md={6}>
            <Tabs
              sx={{
                '& button:focus': {
                  borderTop: '1px solid black',
                  borderLeft: '1px solid black',
                  borderRight: '1px solid black',
                  borderRadius: '5px 5px 0 0',
                  borderBottom: 'none',
                },
              }}
              value={value}
              onChange={handleChange}
              aria-label="basic tabs example"
            >
              <Tab
                sx={{
                  width: '50%',
                }}
                label="Purchase"
                {...a11yProps(0)}
              />
              <Tab sx={{ width: '50%' }} label="Category" {...a11yProps(1)} />
            </Tabs>
            <TabPanel value={value} index={0}>
              <Box flexGrow={2} sx={{ pb: { xs: '70px' } }}>
                <Typography>{data.product.description}</Typography>
              </Box>
              <Box
                sx={{
                  display: { xs: 'flex' },
                  flexDirection: { xs: 'column' },
                  justifyContent: { xs: 'center' },
                  alignItems: { xs: 'center', md: 'flex-end' },
                }}
              >
                <Typography mb={2}>${data.product.price}</Typography>
                <Button
                  disabled={inCart}
                  onClick={() => addProductToCart(1)}
                  sx={{
                    backgroundColor: '#CBA213',
                    height: 50,
                    width: { xs: '300px', md: '150px' },
                    color: 'white',
                  }}
                >
                  {inCart ? 'In Cart' : 'Add to cart'}
                </Button>
              </Box>
            </TabPanel>
            <TabPanel value={value} index={1}>
              <Box sx={{ mb: { xs: '60px' } }}>{data.product.category}</Box>
            </TabPanel>
          </Grid>
        </Grid>

        <Typography
          sx={{
            mt: { xs: '60px', md: '100px', lg: '150px' },
            mb: 5,
            color: 'primary.main',
            fontSize: '32px',
          }}
        >
          Other Product You May Like
        </Typography>
        <Grid container spacing={2}></Grid>
      </Container>
    </Box>
  );
};

export const getServerSideProps = async (context) => {
  const { params } = context;
  const { customId } = params;

  const queryClient = new QueryClient();

  await queryClient.prefetchQuery(
    ['product', customId],
    async () => await getProductData(customId)
  );

  return {
    props: {
      dehydratatedState: dehydrate(queryClient),
    },
  };
};

export default SingleProduct;
