import React, { useState } from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Typography from '@material-ui/core/Typography';
import MainButton from '../../../../../Shared/Components/MainButton';
import { T } from 'Framework/i18n';
import PropTypes from 'prop-types';
import { useHistory } from 'react-router-dom';
import CircularProgress from '@material-ui/core/CircularProgress';
import getImageUrl from '../../../../Utils/getImageUrl';

const useStyles = makeStyles(
    () => ({
        root: {
            display: 'flex',
            flexDirection: 'column',
            gap: '10px',
            width: '70%',
            height: '300px',
            backgroundColor: '#fff',
            padding: '25px',
            borderRadius: '5px',
            margin: '20px',
            boxShadow: '0px 0px 5px 0px rgba(0,0,0,0.2)',
        },
        image: {
            margin: 'auto',
            width: '70%',
            height: '170px',
            '& img': {
                width: '100%',
                height: '100%',
                objectFit: 'contain',
            },
        },
        progress: {
            margin: 'auto',
            width: '70%',
            height: '170px',
        },
        title: {
            wordWrap: 'break-word',
            margin: 'auto',
            height: '30%',
            width: '100%',
        },
        buttonContainer: {
            width: '70%',
            margin: 'auto',
        },
    }),
    { name: 'ItemTile' }
);

const ItemTile = ({ title, linkTo, image }) => {
    const classes = useStyles();
    const history = useHistory();
    const [loadState, setLoadState] = useState(true);

    const handleClick = async link => {
        try {
            history.push(link);
        } catch (e) {
            alert(`could not load configuration: ${linkTo}`);
        }
    };

    return (
        <div className={classes.root}>
            <Typography variant="h6" className={classes.title}>
                {title}
            </Typography>
            {loadState && <CircularProgress className={classes.progress} />}
            <div className={classes.image}>
                <img
                    src={getImageUrl(image)}
                    alt={title}
                    onLoad={() => setLoadState(false)}
                    onError={() => setLoadState(false)}
                />
            </div>
            <div className={classes.buttonContainer}>
                <MainButton fullWidth onClick={() => handleClick(`/identifier:${linkTo}`)}>
                    {T('itemOverview.customize')}
                </MainButton>
            </div>
        </div>
    );
};

ItemTile.defaultProps = {
    title: '',
    linkTo: '',
    image: '',
};

ItemTile.propTypes = {
    title: PropTypes.string,
    linkTo: PropTypes.string,
    image: PropTypes.string,
};

export default ItemTile;
