
import React, { Fragment,lazy, Suspense } from 'react'
import Router from 'next/router'
import { connect } from "react-redux"
import PropTypes from 'prop-types'
import getConfig from 'next/config'
import { withStyles } from '@material-ui/core/styles'
import Typography from '@material-ui/core/Typography'
import Button from '@material-ui/core/Button'
import Avatar from '@material-ui/core/Avatar'
import Chip from '@material-ui/core/Chip'
import OffreRow from "../components/organisms/OffreRow"
import LayoutCompany from "../components/templates/LayoutCompany"
import Link from 'next/link'
import { fetchCompanyRequest, clearCompany, countCompanyViewRequest } from '../actions/companies'
import IconText from '../components/atoms/IconText'
import IconTextInline from '../components/atoms/IconTextInline'
import SimpleCollapse from '../components/atoms/SimpleCollapse'
const VideoVimeo = lazy(() => import('../components/atoms/VideoVimeo'));
//import VideoVimeo from '../components/atoms/VideoVimeo'
import SocialShare from '../components/organisms/SocialShare'
import Loader from '../components/templates/loader'
import _ from "lodash"
import Ar from "lodash/array"
import withWidth from '@material-ui/core/withWidth'
import Hidden from '@material-ui/core/Hidden';
import NoResult from '../components/atoms/NoResult';
import OgHead from '../components/atoms/OgHead';
const renderLoader = () => <p>Chargement</p>;
const styles = theme => ({
    companyContainer: {
        [theme.breakpoints.up('md')]: {
            paddingTop: '5vh',
        },
    },
    primary: {
        color: theme.palette.primary.main,
    },
    root: {
        position: 'relative',
        textAlign: 'center',
        paddingTop: theme.spacing(20),
        justifyContent: 'center',
    },
    container: {
        padding: theme.spacing(0, 3),
        paddingBottom: '10vh',
        [theme.breakpoints.up('md')]: {
            padding: '0 30vw',
        },
    },
    headerContainer: {
        display: 'flex',
        alignItems: 'flex-start',
        justifyContent: 'flex-start',
        margin: theme.spacing(1.5, 0),
    },
    headerContainerDesktop: {
        display: 'flex',
        alignItems: 'flex-start',
        justifyContent: 'space-between',
        margin: theme.spacing(1.5, 0),
        [theme.breakpoints.up('md')]: {
            padding: '0 18vw',
        },
        '& button': {
            marginRight: 0,
        },
    },
    companyInfoContainer: {
        display: 'flex',
    },
    infoContainer: {
        display: 'flex',
        flexDirection: 'column',
        justifyContent: 'flex-start',
        margin: theme.spacing(0, 1.5),
        '& a': {
            textDecoration: 'none',
            width: 'min-content',

        },
        '& span': {
            cursor: 'pointer',
        }
    },
    logoContainer: {
        display: 'flex',
        alignItems: 'center',
        width: 60,
        height: 60,
        backgroundColor: 'white',
        boxShadow: '0px 6px 15px rgba(30, 35, 39, 0.10)',
        border: 'solid 5px white',
        borderRadius: '5px',

    },
    IconTextContainer: {
        paddingTop: theme.spacing(1.5, 0),
    },
    IconTextContainerDesktop: {
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'flex-start',
        width: '100%',
    },
    contentContainer: {
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'flex-start',
        justifyContent: 'flex-start',
        margin: theme.spacing(1.5, 0),
    },
    tagsContainer: {
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        flexWrap: 'wrap',
        width: '100%',
        [theme.breakpoints.up('md')]: {
            justifyContent: 'flex-start',
        },
    },
    shareContainer: {
        display: 'flex',
        flexDirection: 'column',
        alignSelf: 'center',
    },
    discoverContainerOffers: {
        backgroundColor: theme.palette.background.grey,
        paddingBottom: theme.spacing(7),
        minHeight: '30vh',
        '& section': {
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            justifyContent: 'center',
            backgroundColor: theme.palette.background.grey,
        },
        [theme.breakpoints.up('md')]: {
            paddingTop: theme.spacing(2),
            paddingBottom: theme.spacing(2),
        },
    },
    discoverContainerImage: {
        position: 'relative',
    },
    discoverContainerTerritory: {
        backgroundColor: theme.palette.background.grey,
        paddingBottom: theme.spacing(10),
        [theme.breakpoints.up('md')]: {
            paddingTop: theme.spacing(2),
            paddingBottom: theme.spacing(8),
        },
    },
    discoverTerritoryContentContainer: {
        boxShadow: '0px 0px 10px rgba(30, 35, 39, 0.15)',
        transition: 'box-shadow ease-out',
        '&:hover': {
            boxShadow: '0px 6px 16px rgba(30, 35, 39, 0.15)',
            transition: 'box-shadow 2s',
        },
    },

    logo: {
        width: 'inherit',
        height: '100%',
        objectFit: 'contain',
        borderRadius: '0.25em',
    },
    MuiAvatarImg: {
        objectFit: 'contain',
    },
    video: {
        display: 'flex',
        flexDirection: 'column',
        height: '33vh',
        [theme.breakpoints.up('md')]: {
            padding: '0 18vw',
            height: 'auto',
        },
    },
    title: {
        fontSize: '1em',
        fontWeight: '500',
    },
    titleBorder: {
        '&:after': {
            content: '""',
            width: '15px',
            borderBottom: 'solid 2px',
            borderColor: theme.palette.primary.main + '!important',
            display: 'flex',
        },
    },
    text: {
        [theme.breakpoints.up('md')]: {
            fontSize: '1.2em',
        },
    },
    discoverTitle: {
        padding: theme.spacing(3, 0),
        textAlign: 'center',
    },
    contentText: {
        fontSize: '1em',
        fontWeight: '300',
        padding: theme.spacing(1, 0),
        whiteSpace: 'pre-line',
        textAlign: 'justify',
    },
    contentCondition: {
        fontSize: '1em',
        fontWeight: '300',
        textTransform: 'uppercase',
        textAlign: 'center',
        padding: theme.spacing(1.5, 0),
    },
    contentShare: {
        fontSize: '1em',
        fontWeight: '500',
        textAlign: 'center',
    },
    companyName: {
        fontSize: '0.9em',
        fontWeight: '300',
    },
    iconText: {
        marginLeft: 0,
        justifyContent: 'flex-start',
        padding: theme.spacing(0.25, 0),
    },
    iconTextDesktop: {
        marginLeft: 0,
        justifyContent: 'flex-start',
        padding: theme.spacing(0.25, 0),
        width: 'inherit',
    },
    iconTextIcon: {
        color: theme.palette.offerlistitem.icon,
        fontSize: '1em',
        marginRight: theme.spacing(1),
    },
    iconTextText: {
        fontWeight: 'lighter',
        color: theme.palette.secondary.text,
        fontSize: '0.9em',
        paddingLeft: theme.spacing(1),
    },
    iconTextTextDesktop: {
        fontWeight: 'lighter',
        color: theme.palette.offerlistitem.text,
        fontSize: '0.9em',
        paddingLeft: theme.spacing(1),
        width: '100%',
    },
    iconPlay: {
        fontSize: '3.5em',
        color: theme.palette.background.grey,
        position: 'absolute',
        top: 'calc(50% - 0.5em)',
        left: 'calc(50% - 0.5em)',
    },
    websiteLink: {
        textDecoration: 'none',
        color: theme.palette.secondary.text,
    },
    tags: {
        color: theme.palette.primary.dark,
        fontWeight: '300',
        backgroundColor: theme.palette.tags.main,
        textTransform: 'capitalize',
        margin: theme.spacing(1),
    },
    shareIcons: {
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
    },
    button: {
        textTransform: 'inherit',
        marginLeft: theme.spacing(1),
        marginRight: theme.spacing(1),
        padding: theme.spacing(1.2, 2),
        color: theme.palette.secondary.main,
        backgroundColor: theme.palette.primary.important,
        alignSelf: 'center',
    },
    voirOffre: {
        textTransform: 'inherit',
        marginLeft: theme.spacing(1),
        marginRight: theme.spacing(1),
        padding: theme.spacing(1.2, 2),
        color: '#BBBCBD',
        backgroundColor: '#F3F3F4',

    },
    buttonContainer: {
        alignItems: 'right',
    },
    chip: {
        color: theme.palette.secondary.main,
        backgroundColor: theme.palette.primary.main,
        margin: theme.spacing(1, 0),
        fontSize: '1em',
        width: 'fit-content',
    },
    chipHeader: {
        '&:hover, &:active, &:focus': {
            backgroundColor: theme.palette.primary.main,
            boxShadow: 'inherit',
        },

    },
    card: {
        margin: theme.spacing(3, 0),
    },
    discoverTitle: {
        paddingTop: theme.spacing(2),
        '& span': {
            color: theme.palette.primary.main,
        }
    },
    videoVimeo: {
        paddingBottom: '56% !important',
        [theme.breakpoints.up('md')]: {
            paddingBottom: '56% !important',
        }
    },
    territoryTitle: {
        fontWeight: '500',
        padding: theme.spacing(2),
        paddingBottom: 0,
        background: theme.palette.background.default,
    },
    territoryType: {
        fontWeight: '200',
        padding: theme.spacing(2),
        paddingTop: 0,
        background: theme.palette.background.default,
        borderBottomLeftRadius: '5px',
        borderBottomRightRadius: '5px',
    },
});

const CustomTableBody = ({ rowIds, Row, style, className }) => (
    <div style={style} className={className}>
        {rowIds && rowIds.valueSeq().map(r => <Row key={r} griddleKey={r} />)}
    </div>
);

const { publicRuntimeConfig } = getConfig()

class Entreprise extends React.Component {
    state = {
        loading: true,
    };

    componentDidMount() {
        this.props.countCompanyViewRequest(this.props.company.id);
    }

    componentWillUnmount() {
        this.props.clearCompany()
    }

    onVimeoError = (err) => {
        console.error(err);
    }

    render() {
        const { classes, company } = this.props;
        const logoUrl = (company.logo ? publicRuntimeConfig.symphonyUrl + publicRuntimeConfig.cachedMediaUrl + company.logo : publicRuntimeConfig.symphonyUrl + "/img/default_picture_svg")

        const DefaultUrl = publicRuntimeConfig.symphonyUrl + "/img/default_picture_svg"
        const imgUrl = (company.presentation_video && company.presentation_video.thumbnails[0] && company.presentation_video.thumbnails[0].sizes[2]) ? company.presentation_video.thumbnails[0].sizes[2].link : DefaultUrl

        const offre = (company.count_ads == 1) ? company.count_ads + ' offre' : company.count_ads + ' offres'
        const nbOffre = (company.count_ads > 0) ? offre : 'Candidature spontanée'

        const territoryVideoUrlTab = (company.territories[0] && company.territories[0].territory) ? company.territories[0].territory.presentation_video.cdn_url.split('/') : '';
        const territoryVideoId = territoryVideoUrlTab[2]

        const NewLayout = ({ Table }) => (
            <div>
                <Table />
            </div>
        );

        const rowDataSelector = (state, { griddleKey }) => {
            return state
                .get("data")
                .find(rowMap => rowMap.get("griddleKey") === griddleKey)
                .toJSON()
        }

        const { loading } = this.state;
        const socialShareUrl = typeof window !== 'undefined' ? window.location
            : publicRuntimeConfig.frontServerUrl + `/Entreprise/${company.id}`;
        const descriptionVille = company.addresses.billing.city ? company.addresses.billing.city : "";
        const descriptionCompany = company.brand_name ? company.brand_name : "";
        return (
            <LayoutCompany backLink="/Entreprises" companyId={company.id}>
                <OgHead seo_title={company.brand_name && company.brand_name+" recrute des candidats en vidéo | Talents Tube"}
                    seo_description={"Découvrez l'entreprise "+descriptionCompany +" et ses offres en vidéo - "+descriptionVille+ ". Envoyez votre candidature spontanée en vidéo."}
                    seo_url={socialShareUrl}
                    image={imgUrl}
                ></OgHead>
                {(!_.isEmpty(company.ads) || company.presentation_video) && (
                    <div className={classes.companyContainer}>
                        <Hidden smDown>
                            <section className={classes.headerContainerDesktop}>
                                <div className={classes.companyInfoContainer}>
                                    <div className={classes.logoContainer}>
                                        <Avatar className={classes.logo} classes={{ img: classes.MuiAvatarImg }} src={logoUrl} alt="companylogo" />
                                    </div>
                                    <div className={classes.infoContainer}>
                                        <Typography gutterBottom className={classes.text}>
                                            {company.brand_name && company.brand_name}
                                        </Typography>

                                        {(nbOffre != 'Candidature spontanée') ?
                                            (
                                                <Link href="#discover" >
                                                    <Chip label={nbOffre} className={classes.chip + ' ' + classes.chipHeader} />
                                                </Link>
                                            )
                                            :
                                            (<Chip label={nbOffre} className={classes.chip + ' ' + classes.chipHeader} />)
                                        }
                                        
                                        {/* ville */}
                                    </div>
                                </div>
                                <div className={classes.buttonContainer}>
                                
                                <Link href="#discover"  >
                                            <Button
                                                variant="contained"
                                                className={classes.voirOffre + ' cypButtonApply'}
                                            >Voir les offres</Button>
                                            
                                </Link>
                                <Button
                                    variant="contained"
                                    className={classes.button}
                                    onClick={() => Router.push(`/Reponse?companyId=${company.id}`)}
                                >Candidature spontanée</Button>
                                </div>
                            </section>
                        </Hidden>
                        {company.presentation_video &&  <Suspense fallback={renderLoader()}><VideoVimeo videoId={Ar.last(_.split(company.presentation_video.cdn_url, '/'))} autoplay='1' /></Suspense>}
                        <div className={classes.container}>
                            <Hidden mdUp>
                                <section className={classes.headerContainer}>
                                    <div className={classes.logoContainer}>
                                        <Avatar className={classes.logo} classes={{ img: classes.MuiAvatarImg }} src={logoUrl} alt="companylogo" />
                                    </div>
                                    <div className={classes.infoContainer}>
                                        <Typography gutterBottom className={classes.text}>
                                            {company.brand_name && company.brand_name}
                                        </Typography>
                                        {(nbOffre != 'Candidature spontanée') ?
                                            (
                                                <a href="#discover" className={classes.discoverAnchor}>
                                                    <Chip label={nbOffre} className={classes.chip + ' ' + classes.chipHeader} />
                                                </a>
                                            )
                                            :
                                            (<Chip label={nbOffre} className={classes.chip + ' ' + classes.chipHeader} />)
                                        }
                                        {/* ville */}
                                    </div>
                                </section>
                            </Hidden>

                            <Hidden mdUp>
                                <section className={classes.IconTextContainer}>
                                    {(company.addresses.billing.city) ?
                                        (<IconText classes={{ root: classes.iconText, icon: classes.iconTextIcon, text: classes.iconTextText }} variant="location_on" text={company.addresses.billing.city} />)
                                        : ''
                                    }
                                    {(company.website) ?
                                        (
                                            <a  href={company.website} className={classes.websiteLink} rel="noopener" target="_blank" rel="noopener">
                                                <IconText classes={{ root: classes.iconText, icon: classes.iconTextIcon, text: classes.iconTextText }} variant="business_center" text={!!company.website ? company.website : "website"} />
                                            </a>
                                        )
                                        : ''
                                    }
                                </section>
                            </Hidden>

                            <section className={classes.contentContainer}>
                                <Typography gutterBottom className={classes.title + ' ' + classes.titleBorder}>
                                    Présentation
                                </Typography>

                                <Hidden smDown>
                                    <section className={classes.IconTextContainerDesktop}>
                                        <IconTextInline classes={{ icon: classes.iconTextIcon, text: classes.iconTextText }} variant="location_on" text={company.addresses.billing.city} />
                                        {(company.website) ?
                                            (
                                                <a  href={!!company.website ? company.website : "website"} target="_blank" rel="noopener" className={classes.websiteLink}><IconTextInline classes={{ icon: classes.iconTextIcon, text: classes.iconTextText }} variant="business_center" text={!!company.website ? company.website : "website"} /></a>
                                            )
                                            : ''
                                        }

                                    </section>
                                </Hidden>

                                <SimpleCollapse>
                                    <Typography gutterBottom className={classes.contentText}>
                                        {company.description}
                                    </Typography>
                                    <section className={classes.tagsContainer}>
                                        {company.public_tag.map((label, index) => {
                                            return (
                                                <Chip label={label} className={classes.tags} key={index} />
                                            );
                                        })}
                                    </section>
                                </SimpleCollapse>

                                <div className={classes.shareContainer}>
                                    <Button
                                        variant="contained"
                                        className={classes.button}
                                        onClick={() => Router.push(`/Reponse?companyId=${company.id}`)}
                                    >Candidature spontanée</Button>
                                    
                                    <Typography className={classes.contentCondition}>
                                        ou
                                    </Typography>
                                    <Typography gutterBottom className={classes.contentShare}>
                                        Partagez l'entreprise sur votre réseau
                                </Typography>
                                    <section className={classes.ShareIcons}>
                                        <SocialShare url={socialShareUrl} />
                                    </section>
                                </div>
                            </section>
                        </div>

                        {
                            !_.isEmpty(company.ads) ? (
                                <div className={classes.container + ' ' + classes.discoverContainerOffers} id="discover">
                                    <Typography gutterBottom className={classes.title + ' ' + classes.discoverTitle}>
                                        Les offres d'emploi pour <span>{company.brand_name && company.brand_name}</span>
                                    </Typography>
                                    {company.loading ?
                                        (<Loader />)
                                        : !_.isEmpty(company.ads) ? (
                                            _.filter(company.ads, { 'status': 'PUBLISHED' }).map((ad, index) => {
                                                return (
                                                    <OffreRow rowData={ad} company={company} classes={{ card: classes.card }} key={index} />
                                                );
                                            })
                                        ) : (<NoResult text='Aucun résultat.' />)}
                                </div>
                            ) : ''
                        }

                        {
                            !_.isEmpty(company.territories) ? (
                                <div className={classes.container + ' ' + classes.discoverContainerTerritory}>
                                    <section>
                                        <Typography gutterBottom className={classes.title + ' ' + classes.discoverTitle} align="center">
                                            Découvrir le <span className={classes.primary}>territoire</span>
                                        </Typography>
                                        <section className={classes.discoverTerritoryContentContainer}>
                                            <VideoVimeo classesOverride={classes.videoVimeo} videoId={territoryVideoId} autoplay='0' />
                                            <Typography className={classes.territoryTitle}>
                                                {(company.territories) ? company.territories[0].territory.brand_name : ''}
                                            </Typography>
                                            <Typography className={classes.territoryType} gutterBottom>
                                                {(company.territories) ? company.territories[0].territory.extra.terType : ''}
                                            </Typography>
                                        </section>
                                    </section>
                                </div>
                            ) : ''
                        }

                    </div>
                )}
            </LayoutCompany>
        );
    }

}

Entreprise.getInitialProps = function (context) {
    const { id } = context.query

    context.store.dispatch(fetchCompanyRequest(id))

    return id
}

function mapStateToProps(state) {
    return {
        company: state.company
    };
}

Entreprise.propTypes = {
    classes: PropTypes.object.isRequired,
};

export default withStyles(styles)(connect(mapStateToProps, { fetchCompanyRequest, clearCompany, countCompanyViewRequest })(withWidth()(Entreprise)));
