import React, { useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import ItemTile from '../../Configurator/Components/ItemTile/ItemTile';
import { makeStyles, useTheme } from '@material-ui/core/styles';
import AppBar from '@material-ui/core/AppBar';
import ButtonBase from '@material-ui/core/ButtonBase';
import Typography from '@material-ui/core/Typography';
import Grid from '@material-ui/core/Grid';
import useMediaQuery from '@material-ui/core/useMediaQuery';
import { T } from 'Framework/i18n';
import { lazyFetch } from '../../../Utils/Request/lazyFetch';
import { Pagination } from '@material-ui/lab';
import GlobalLoader from '../../../Shared/Containers/GlobalLoader';
import { withGlobalLoader } from '../../../Reducers/UI/Actions';
import { useDispatch } from 'react-redux';

const useStyles = makeStyles(
    theme => ({
        container: {
            marginTop: '80px',
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            width: '70%',
            margin: 'auto',
            [theme.breakpoints.down('sm')]: {
                width: '95%',
            },
        },
        itemContainer: {
            minWidth: '100%',
            backgroundColor: '#C4C4C4',
            padding: '30px',
            marginBottom: '30px',
            borderRadius: '10px',
            [theme.breakpoints.down('sm')]: {
                minWidth: '85%',
                maxWidth: '95%',
            },
        },
        gridContainer: {
            margin: 'auto',
        },
        categoryContainer: {
            display: 'flex',
            gap: '15px',
            width: '100%',
            marginTop: '40px',
            marginBottom: '30px',
            overflowX: 'auto',
            [theme.breakpoints.down('md')]: {
                marginTop: '20px',
            },
        },
        categoryButton: {
            backgroundColor: '#ededed',
            color: '#000',
            borderRadius: '50px',
            padding: '20px',
            '&.active': {
                backgroundColor: theme.palette.primary.main,
                color: '#fff',
            },
        },
        header: {
            minHeight: '64px',
            display: 'flex',
            justifyContent: 'center',
            paddingLeft: '25px',
        },
        paginationContainer: {
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            marginBottom: '10px',
        },
    }),
    { name: 'ItemOverview' }
);

export const ItemOverview = ({ pageSize }) => {
    const classes = useStyles();
    const theme = useTheme();
    const isMobile = useMediaQuery(theme.breakpoints.down('sm'));

    const [items, setItems] = useState([]);
    const [categories, setCategories] = useState([]);
    const [chosenCategory, setChosenCategory] = useState(0);
    const [pagination, setPagination] = useState({
        count: 0,
        from: 0,
    });
    const dispatch = useDispatch();

    const fetchItems = async () => {
        const params = {
            offset: pagination.from,
            limit: pageSize,
        };
        if (chosenCategory) {
            params['item-classifications'] = `[${chosenCategory}]`;
        }
        const response = await dispatch(
            withGlobalLoader(() =>
                lazyFetch({
                    url: `items`,
                    params,
                })
            )
        );
        return response.data;
    };

    const fetchCategories = async () => {
        const response = await dispatch(() => lazyFetch('item-classifications'));
        return response.data;
    };

    useEffect(() => {
        (async () => {
            setCategories(await fetchCategories());
        })();
    }, []);

    useEffect(() => {
        setPagination({ ...pagination, from: 0 });
    }, [chosenCategory]);

    useEffect(() => {
        (async () => {
            const { data: items, count } = await fetchItems();
            setItems(items);
            setPagination({ ...pagination, count: Math.ceil(count / pageSize) });
        })();
    }, [pagination.from, chosenCategory]);

    const onClickCategory = identifier => {
        if (chosenCategory === identifier) return setChosenCategory('');
        setChosenCategory(identifier);
    };

    const handlePageChange = (event, page) => {
        const from = (page - 1) * pageSize;
        setPagination({ ...pagination, from: from });
    };

    const renderCategories = () => {
        return (
            <div className={classes.categoryContainer}>
                {categories.map(category => (
                    <ButtonBase
                        className={clsx(classes.categoryButton, chosenCategory === category.id && 'active')}
                        key={category.identifier}
                        onClick={() => onClickCategory(category.id)}
                    >
                        {category.translated_title}
                    </ButtonBase>
                ))}
            </div>
        );
    };

    const renderPagination = () => {
        return (
            <div className={classes.paginationContainer}>
                <Pagination
                    count={pagination.count}
                    color="primary"
                    onChange={handlePageChange}
                    size={isMobile ? 'small' : 'large'}
                />
            </div>
        );
    };

    const renderItems = () => {
        if (items.length < 1) {
            return (
                <div>
                    <Typography variant="body2">{T('itemOverview.noItems')}</Typography>
                </div>
            );
        } else {
            return (
                <div className={classes.itemContainer}>
                    {renderPagination()}
                    <Grid container className={classes.gridContainer}>
                        {items.map((item, index) => (
                            <Grid item key={item.identifier} xs={12} sm={6} md={3}>
                                <ItemTile
                                    title={item.title}
                                    index={index}
                                    image={item.thumbnail}
                                    linkTo={item.identifier}
                                    key={item.identifier}
                                />
                            </Grid>
                        ))}
                    </Grid>
                </div>
            );
        }
    };

    return (
        <div>
            <AppBar color="default" className={classes.header}>
                <Typography variant="h5">{T('itemOverview.title')}</Typography>
            </AppBar>
            <div className={classes.container}>
                {!!categories.length && renderCategories()}
                {!!items.length && renderItems()}
            </div>
            <GlobalLoader />
        </div>
    );
};

ItemOverview.propTypes = {
    pageSize: PropTypes.number,
};

ItemOverview.defaultProps = {
    pageSize: 8,
};

export default ItemOverview;
