import { FC, useState, useEffect } from 'react';
import { Helmet } from 'react-helmet-async';
import { useQuery } from 'react-query';
import { useNavigate } from 'react-router-dom';

import Box from '@material-hu/mui/Box';
import CircularProgress from '@material-hu/mui/CircularProgress';
import Container from '@material-hu/mui/Container';
import Divider from '@material-hu/mui/Divider';
import Typography from '@material-hu/mui/Typography';

import FilterProducts from 'src/pages/dashboard/recognitions/components/FilterProducts';
import IdeasSearch from 'src/pages/dashboard/recognitions/components/IdeasSearch';
import ModuleHeader from 'src/pages/dashboard/recognitions/components/ModuleHeader';
import ProductCard from 'src/pages/dashboard/recognitions/components/ProductCard';
import { useTranslation } from 'src/pages/dashboard/recognitions/i18n';
import { recognitionsKeys } from 'src/pages/dashboard/recognitions/queries';
import { recognitionsRoutes } from 'src/pages/dashboard/recognitions/routes';
import { getProductsList } from 'src/services/recognitions';
import { filterByRange, getUserId } from 'src/utils/recognitions';

import GoBackButton from 'src/components/dashboard/GoBackButton';

const Products: FC = () => {
  const { t } = useTranslation();
  const userId = getUserId();
  const navigate = useNavigate();

  const [products, setProducts] = useState(null);
  const [filteredProducts, setFilteredProducts] = useState(null);
  const [searchInput, setSearchInput] = useState('');
  const [openFilterDialog, setOpenFilterDialog] = useState(false);
  const [minSones, setMinSones] = useState('');
  const [maxSones, setMaxSones] = useState('');
  const [minQuantity, setMinQuantity] = useState('');
  const [maxQuantity, setMaxQuantity] = useState('');

  const handleOpenFilterDialog = () => setOpenFilterDialog(true);

  const { isLoading } = useQuery(
    recognitionsKeys.products(),
    () => getProductsList(),
    {
      onSuccess: data => {
        setProducts(data.data.DataProducts);
        setFilteredProducts(data.data.DataProducts);
      },
    },
  );

  const applyFiltersAndSearch = () => {
    let sorted = [...products];
    sorted = filterByRange(sorted, 'priceSones', minSones, maxSones);
    sorted = filterByRange(sorted, 'quantity', minQuantity, maxQuantity);
    const lowerCaseSearch = searchInput.toLowerCase();
    sorted = sorted.filter(product =>
      product.name.toLowerCase().includes(lowerCaseSearch),
    );
    setFilteredProducts(sorted);
  };

  useEffect(() => {
    if (products) {
      applyFiltersAndSearch();
    }
  }, [searchInput, minSones, maxSones, minQuantity, maxQuantity, products]);

  const onApplyFilters = data => {
    setMinSones(data.minSones);
    setMaxSones(data.maxSones);
    setMinQuantity(data.minQuantity);
    setMaxQuantity(data.maxQuantity);
  };

  const handleSearchInputChange = event => setSearchInput(event.target.value);

  const handleGoBack = () => navigate(recognitionsRoutes.home());

  if (!userId) {
    navigate(recognitionsRoutes.home());
  }

  return (
    <>
      <Helmet>
        <title>{t('RECOGNITIONS')}</title>
      </Helmet>
      <Box
        sx={{
          backgroundColor: 'background.default',
          minHeight: '100%',
          pt: 3,
          pb: 3,
        }}
      >
        <Container maxWidth="md">
          <GoBackButton onClick={handleGoBack} />
          <Box sx={{ mt: 3, mb: 3 }}>
            <Box
              sx={{
                p: 3,
                width: '100%',
                backgroundColor: '#ffffff',
                borderRadius: '10px',
              }}
            >
              <ModuleHeader title={t('CATALOGUE')} />
              <Divider sx={{ borderBottomWidth: 'medium', mt: 2, mb: 3 }} />
              {(isLoading || !products) && (
                <Box sx={{ textAlign: 'center' }}>
                  <CircularProgress />
                </Box>
              )}
              {!isLoading && filteredProducts && (
                <Box>
                  <IdeasSearch
                    searchInput={searchInput}
                    handleOnChange={handleSearchInputChange}
                    onOpenIdeaFilter={handleOpenFilterDialog}
                    placeholder={t('SEARCH_PRODUCTS')}
                  />
                  <Box
                    sx={{
                      display: 'flex',
                      flexWrap: 'wrap',
                    }}
                  >
                    {filteredProducts.length === 0 && (
                      <Box
                        sx={{
                          display: 'flex',
                          width: '100%',
                          justifyContent: 'center',
                          mt: 4,
                        }}
                      >
                        <Typography
                          color="textSecondary"
                          variant="subtitle2"
                        >
                          {t('NO_PRODUCTS_FOUND')}
                        </Typography>
                      </Box>
                    )}
                    {filteredProducts.length > 0 && (
                      <>
                        {filteredProducts.map((product, index) => (
                          <ProductCard
                            key={index}
                            product={product}
                          />
                        ))}
                      </>
                    )}
                  </Box>
                </Box>
              )}
            </Box>
          </Box>
          {openFilterDialog && (
            <FilterProducts
              open={openFilterDialog}
              onClose={() => setOpenFilterDialog(false)}
              onApplyFilters={onApplyFilters}
              minSones={minSones}
              maxSones={maxSones}
              minQuantity={minQuantity}
              maxQuantity={maxQuantity}
            />
          )}
        </Container>
      </Box>
    </>
  );
};

export default Products;
