import React, { Fragment,lazy, Suspense } from 'react'
import Router from 'next/router'
import { withStyles } from '@material-ui/core/styles';
import getConfig from 'next/config'
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 KeyboardArrowleftIcon from '@material-ui/icons/PlayArrowRounded';
import IconText from '../atoms/IconText';
import IconTextInline from './../atoms/IconTextInline';
import SocialShare from './SocialShare';
import SimpleCollapse from '../atoms/SimpleCollapse';
import _ from "lodash/string";
import Ar from "lodash/array";
import Hidden from '@material-ui/core/Hidden';
import Link from 'next/link'
import withWidth, { isWidthUp } from '@material-ui/core/withWidth'
const VideoVimeo = lazy(() => import('../atoms/VideoVimeo'));
//import VideoVimeo from '../atoms/VideoVimeo'
import OgHead from '../atoms/OgHead'
import JobPosting from '../atoms/JobPosting'
import Moment from 'react-moment';
const renderLoader = () => <p>Chargement</p>;
const styles = theme => ({
    primary: {
        color: theme.palette.primary.main,
    },
    root: {
        position: 'relative',
        textAlign: 'center',
        paddingTop: theme.spacing(20),
        justifyContent: 'center',
    },
    container: {
        padding: theme.spacing(0, 3),
        [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: '16px 18vw',
        },
        '& button': {
            marginRight: 0,
        },
    },
    offerInfoContainer: {
        display: 'flex',
    },
    buttonContainer: {
        alignItems: 'right',
    },
    infoContainer: {
        display: 'flex',
        flexDirection: 'column',
        margin: theme.spacing(0, 1.5),
        '& a': {
            textDecoration: 'none',
            color: theme.palette.primary.dark,
        }
    },
    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),
        height: '100%',
    },
    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',
    },
    discoverContainerCompany: {
        backgroundColor: theme.palette.background.grey,
        paddingBottom: theme.spacing(2),
        '& section': {
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            justifyContent: 'center',
            backgroundColor: theme.palette.background.grey,
        },
    },
    discoverContainerImage: {
        cursor: 'pointer',
        position: 'relative',
        '& img': {
            width: '100%',
            borderRadius: '5px',
            boxShadow: '0 6px 10px 0 rgba(0, 0, 0, 0.04), 0 1px 18px 0 rgba(0, 0, 0, 0.03), 0 3px 5px -1px rgba(0, 0, 0, 0.04)',
            '&:hover': {
                boxShadow: '0 6px 10px 0 rgba(0, 0, 0, 0.15), 0 1px 18px 0 rgba(0, 0, 0, 0.10), 0 3px 5px -1px rgba(0, 0, 0, 0.15)',
                transition: 'box-shadow 2s',
            }
        },
        [theme.breakpoints.up('md')]: {
            width: '100%',
        },
    },
    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.10)',
    },
    logo: {
        width: 'inherit',
        height: '100%',
        objectFit: 'contain',
        borderRadius: '0.25em',
    },
    MuiAvatarImg: {
        objectFit: 'contain',
    },
    title: {
        fontSize: '1.3em',
        fontWeight: '500',
        [theme.breakpoints.up('md')]: {
            paddingTop: theme.spacing(2),
        },
    },
    offreTitle: {
        [theme.breakpoints.up('md')]: {
            fontSize: '1.3em',
            fontWeight: '600',
        },
    },
    discoverTitle: {
        padding: theme.spacing(3, 0),
    },
    voirEntreprise: {
        textTransform: 'inherit',
        marginLeft: theme.spacing(1),
        marginRight: theme.spacing(1),
        padding: theme.spacing(1.2, 2),
        color: '#BBBCBD',
        backgroundColor: '#F3F3F4',

    },
    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: '1.3em',
        fontWeight: '300',
        [theme.breakpoints.up('md')]: {
            fontSize: '1em',
        },
    },
    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: '1.3em',
    },
    iconTextText: {
        fontWeight: 'lighter',
        color: theme.palette.offerlistitem.text,
        fontSize: '1em',
        paddingLeft: theme.spacing(1),
    },
    iconTextTextDesktop: {
        fontWeight: 'lighter',
        color: theme.palette.offerlistitem.text,
        fontSize: '1em',
        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)',
    },
    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,
    },
    chip: {
        color: theme.palette.secondary.main,
        backgroundColor: theme.palette.secondary.important,
        padding: theme.spacing(1),
        margin: theme.spacing(1, 0),
        fontSize: '1em',
        [theme.breakpoints.up('md')]: {
            marginRight: 'auto',
        },
    },
    videoOffre: {
        [theme.breakpoints.up('md')]: {
            paddingBottom: '35%', /* 16:9 */
        },
    },
    videoTerritory: {
        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 { publicRuntimeConfig } = getConfig()

function OffreDetail(props) {
    let { classes, offre, isCandidature } = props;
    const logoUrl = (offre.company ? publicRuntimeConfig.symphonyUrl + publicRuntimeConfig.cachedMediaUrl + offre.company.logo : "/static/images/defaultdefault_picture_company.svg/")
    const DefaultUrl = "/static/images/default/default_picture_company.svg"
    const imgUrl = (offre.company && offre.company.presentation_video && offre.company.presentation_video.thumbnails && offre.company.presentation_video.thumbnails[0] && offre.company.presentation_video.thumbnails[0].sizes[2]) ? offre.company.presentation_video.thumbnails[0].sizes[2].link : DefaultUrl
    const imgUrlDesktop = (offre.company && offre.company.presentation_video && offre.company.presentation_video.thumbnails && offre.company.presentation_video.thumbnails[0] && offre.company.presentation_video.thumbnails[0].sizes[4]) ? offre.company.presentation_video.thumbnails[0].sizes[4].link : DefaultUrl
    const socialShareUrl = typeof window !== 'undefined' ? window.location : publicRuntimeConfig.frontServerUrl + `/Offre/${offre.id}-${_.kebabCase(offre.title)}`;
    const entrepriseLink = (offre.company && `/Entreprise/${offre.company.id}-${_.kebabCase(offre.company.brand_name)}`);
    const territoryVideoUrlTab = (offre.territories && offre.territories[0] && offre.territories[0].territory) ? offre.territories[0].territory.presentation_video.cdn_url.split('/') : '';
    const territoryVideoId = territoryVideoUrlTab[2]
    let descriptionSEO = ""
    let titleSEO = ""
    offre.company.brand_name ? descriptionSEO += offre.company.brand_name : ""
    descriptionSEO +=  " recrute en vidéo un(e) "+offre.title
    titleSEO =  "Offre d'emploi vidéo "+offre.title 
    offre.location.gmap_address.formatted_address ? descriptionSEO += ", "+offre.location.gmap_address.formatted_address : ""
    offre.location.gmap_address.formatted_address ? titleSEO += ", "+offre.location.gmap_address.formatted_address : ""
    offre.company.brand_name ? titleSEO += " - "+offre.company.brand_name : ""
    descriptionSEO +=  ". Envoyez votre candidature en vidéo. "
    titleSEO += " | Talents Tube "
    let jobVille=""
    let jobDpt=""
    let jobPays=""
    let  jobContract =""
    let  tempsType =""
    let  tempsTypeFr =""
    offre.location.gmap_address.address_components[0] ? jobVille = offre.location.gmap_address.address_components[0].long_name: jobVille=""
    offre.location.gmap_address.address_components[1] ? jobDpt = offre.location.gmap_address.address_components[1].long_name: jobDpt=""
    offre.location.gmap_address.address_components[3] ? jobPays = offre.location.gmap_address.address_components[3].long_name: jobPays=""
    // offre.location.gmap_address ? jobAdr = location.gmap_address.adr_address: jobAdr=""
    offre.extra.contract_type ? jobContract = offre.extra.contract_type : jobContract =""
    offre.extra.temps_type ? tempsType = offre.extra.temps_type : tempsType =""
    if(tempsType=="PART_TIME"){
        tempsTypeFr="Temps partiel"
    }else if(tempsType=="FULL_TIME") {
        tempsTypeFr="Plein temps"
    }else if(tempsType=="MIX_TIME") {

    }
    return (
        <Fragment>
            {/* {offre.public_tag.map((label, index) => {
                 descriptionSEO += label+", "
            })} */}
            
            <OgHead seo_title={titleSEO}
                seo_description={descriptionSEO}
                seo_url={socialShareUrl}
                image={imgUrlDesktop}
            ></OgHead>
            <JobPosting job_title={offre.title}
                job_description={offre.description}
                job_brand= {offre.company.brand_name && offre.company.brand_name}
                job_brand_link= {entrepriseLink}
                job_title = {offre.title}
                job_location = {offre.location.gmap_address.formatted_address}
                job_ville = {jobVille}
                job_dept = {jobDpt}
                job_pays = {jobPays}
                job_adr = {offre.location.gmap_address.formatted_address}
                job_date = {offre.published_at}
                job_date_fin = {offre.unpublished_at}
                job_temps_type= {tempsType}
                job_contract_type= {jobContract}
            ></JobPosting>
            {offre.video && (
                <Fragment>
                    <Hidden smDown>
                        <section className={classes.headerContainerDesktop}>
                            <div className={classes.offerInfoContainer}>

                                <a href={entrepriseLink} >
                                    <div className={classes.logoContainer}>

                                        <Avatar className={classes.logo} classes={{ img: classes.MuiAvatarImg }}
                                            src={logoUrl} alt={offre.company.brand_name && offre.company.brand_name} />

                                    </div>
                                </a>
                                <div className={classes.infoContainer}>
                                    <Typography gutterBottom className={classes.offreTitle}>
                                         {offre.title}   {/*- publié le <Moment format="DD/MM/YYYY" date={offre.published_at} /> */}
                                         
                                    </Typography>
                                    <a href={entrepriseLink} >
                                        <Typography gutterBottom variant="subtitle1" className={classes.companyName}>
                                        {offre.company.brand_name  ? offre.company.brand_name  : ""}
                                        </Typography>
                                    </a>
                                    {offre.is_promoted && (
                                        <Chip label="Pourvue" className={classes.chip} />
                                    )}
                                    {/* ville */}
                                </div>
                            </div>
                            <div className={classes.buttonContainer}>
                            {!!!offre.is_promoted && (
                                <Link href={`/Entreprise/${offre.company.id}-${_.kebabCase(offre.company.brand_name)}`} >
                                    <Button
                                        variant="contained"
                                        className={classes.voirEntreprise + ' cypButtonApply'}
                                    >Voir l'entreprise</Button>
                                    
                                </Link>
                                
                                
                            )}
                            {!!!offre.is_promoted && (
                                <Link href={`/Reponse?adId=${offre.id}`}>
                                    <Button
                                        variant="contained"
                                        className={classes.button + ' cypButtonApply'}
                                    >Postuler</Button>
                                    
                                </Link>
                                
                                
                            )}
                            </div>
                            
                        </section>
                    </Hidden>
                    <Suspense fallback={renderLoader()}>   
                        <VideoVimeo  {...isCandidature == 'true' ? 'classes={{ video: classes.videoOffre }}' : ''} videoId={Ar.last(_.split(offre.video.cdn_url, '/'))} autoplay='1' />
                    </Suspense>            
                    <div className={classes.container}>
                        <Hidden mdUp>
                            <section className={classes.headerContainer}>
                                <div className={classes.logoContainer}>

                                    <a href={entrepriseLink} >
                                        <Avatar className={classes.logo} classes={{ img: classes.MuiAvatarImg }}
                                            src={logoUrl} alt="companylogo" />
                                    </a>

                                </div>
                                <div className={classes.infoContainer}>
                                    <Typography gutterBottom variant="h5" component="h1" className={classes.title}>
                                        {offre.title}
                                    </Typography>
                                    <a href={entrepriseLink}  >
                                        <Typography gutterBottom variant="subtitle1" className={classes.text}>
                                            {offre.company.brand_name && offre.company.brand_name}
                                        </Typography>
                                    </a>
                                    {/* ville */}
                                </div>
                            </section>
                            <section className={classes.IconTextContainer}>
                                {offre.is_promoted && (<Chip label="Pourvue" className={classes.chip} />)}
                                {offre.extra && (<IconText classes={{ root: classes.iconText, icon: classes.iconTextIcon, text: classes.iconTextText }} variant="assignment" text={offre.extra.contract_type} />)}
                                {tempsTypeFr && (<IconText classes={{ root: classes.iconText, icon: classes.iconTextIcon, text: classes.iconTextText }} variant="watch_later" text={tempsTypeFr} />)}
                                {offre.location && offre.location.gmap_address && (<IconText classes={{ root: classes.iconText, icon: classes.iconTextIcon, text: classes.iconTextText }} variant="location_on" text={offre.location.gmap_address.formatted_address} />)}
                                {offre.beneficiaire  && (<IconText classes={{ root: classes.iconText, icon: classes.iconTextIcon, text: classes.iconTextText }} variant="business" text={offre.beneficiaire} />)}
                            </section>
                        </Hidden>


                        <div className={classes.contentContainer}>
                            <Typography gutterBottom className={classes.title}>
                                Détails de l'offre d'emploi
                                </Typography>
                            <Hidden smDown>
                                <section className={classes.IconTextContainerDesktop}>
                                    <IconTextInline classes={{ icon: classes.iconTextIcon, text: classes.iconTextText }} variant="assignment" text={offre.extra.contract_type} />
                                    {tempsTypeFr ?<IconTextInline classes={{ icon: classes.iconTextIcon, text: classes.iconTextText }} variant="watch_later" text={tempsTypeFr } />:""}
                                    <IconTextInline classes={{ icon: classes.iconTextIcon, text: classes.iconTextText }} variant="location_on" text={offre.location.gmap_address.formatted_address} />
                                    {offre.beneficiaire && (<IconTextInline classes={{ icon: classes.iconTextIcon, text: classes.iconTextText }} variant="business" text={offre.beneficiaire} /> )}
                                </section>
                            </Hidden>
                            <SimpleCollapse>
                                <Typography gutterBottom className={classes.contentText}>
                                    {offre.description}
                                </Typography>
                                <section className={classes.tagsContainer}>
                                    {offre.public_tag.map((label, index) => {
                                        return (
                                            <Chip label={label} className={classes.tags} key={index} />
                                        );
                                    })}
                                </section>
                            </SimpleCollapse>

                            {!offre.is_promoted && (
                                <div className={classes.shareContainer}>
                                    <Link href={`/Reponse?adId=${offre.id}`}>
                                        <Button
                                            cyp="ButtonApply"
                                            variant="contained"
                                            className={classes.button}

                                        >Postuler</Button>
                                    </Link>
                                    <Typography className={classes.contentCondition}>
                                        ou
                                    </Typography>
                                    <Typography gutterBottom className={classes.contentShare}>
                                        Partagez l'offre sur votre réseau
                                    </Typography>
                                    <section className={classes.ShareIcons}>
                                        <SocialShare url={socialShareUrl} />
                                    </section>
                                </div>
                            )}
                        </div>
                    </div>
                    {offre.company.presentation_video && !offre.is_promoted && (
                        <div className={classes.container + ' ' + classes.discoverContainerCompany}>
                            <section>
                                <Typography gutterBottom className={classes.title + ' ' + classes.voirEntreprise} align="center">
                                    Voir l'entreprise <span className={classes.primary}>{offre.company.brand_name && offre.company.brand_name}</span>
                                </Typography>

                                <a href={entrepriseLink}>
                                    <div className={classes.discoverContainerImage}>
                                        <img src={isWidthUp('sm', props.width) ? imgUrlDesktop : imgUrl} alt={offre.company.brand_name && offre.company.brand_name} />
                                        <KeyboardArrowleftIcon className={classes.iconPlay} />
                                    </div>
                                </a>
                            </section>
                        </div>
                    )}
                    {offre.territories && territoryVideoId && (
                        <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}>
                                    <Suspense fallback={renderLoader()}>
                                        <VideoVimeo classesOverride={classes.videoTerritory} videoId={territoryVideoId} autoplay='0' />
                                    </Suspense>
                                    <Typography className={classes.territoryTitle}>
                                        {(!!!offre.territories) ? offre.territories[0].territory.brand_name : ''}
                                    </Typography>
                                    <Typography className={classes.territoryType} gutterBottom>
                                        {(!!!offre.territories) ? offre.territories[0].territory.extra.terType : ''}
                                    </Typography>
                                </section>
                            </section>
                        </div>
                    )
                    }
                </Fragment>
            )}
        </Fragment>
    )
}
export default withStyles(styles)(withWidth()(OffreDetail));