/*Copyright (C) 2019 Centro de Computacao Cientifica e Software Livre
Departamento de Informatica - Universidade Federal do Parana

This file is part of Plataforma Integrada MEC.

Plataforma Integrada MEC is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Plataforma Integrada MEC is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with Plataforma Integrada MEC.  If not, see <http://www.gnu.org/licenses/>.*/

import React, {useState, useContext, useEffect} from 'react';
import styled from 'styled-components'
import Button from '@material-ui/core/Button';
import IconButton from '@material-ui/core/IconButton';
import PhotoCamera from '@material-ui/icons/PhotoCamera';
import Tooltip from '@material-ui/core/Tooltip';
import CustomizedBreadcrumbs from '../Components/TabPanels/Breadcrumbs.js'
import {Link} from 'react-router-dom';
import Popover from '@material-ui/core/Popover';
import { Store } from '../Store.js';
import EditIcon from '@material-ui/icons/Edit';
import CheckDecagram from '../img/check-decagram-gray.svg'
import Tabs from '@material-ui/core/Tabs';
import Tab from '@material-ui/core/Tab';
import Paper from '@material-ui/core/Paper';
import TabPanelAtividades from '../Components/TabPanels/UserPageTabs/PanelAtividades.js'
import TabPanelMeusRecursos from '../Components/TabPanels/UserPageTabs/PanelMeusRecursos.js'
import TabPanelFavoritos from '../Components/TabPanels/UserPageTabs/PanelFavoritos.js'
import TabPanelColecoes from '../Components/TabPanels/UserPageTabs/PanelColecoes.js'
import TabPanelRede from '../Components/TabPanels/UserPageTabs/PanelRede.js'
import TabPanelCuradoria from '../Components/TabPanels/UserPageTabs/PanelCuradoria.js'
import axios from 'axios'
import {apiUrl, apiDomain} from '../env';
import ModalAlterarAvatar from '../Components/ModalAlterarAvatar.js'
import Grid from '@material-ui/core/Grid';
import noAvatar from "../img/default_profile.png";
import {HeaderContainer, UserProfileContainer, UserProfileInfoDiv, CoverContainer, CheckTeacherDiv, StyledTabs, RodapeDiv, NavBarContentContainer, BackgroundDiv} from '../Components/TabPanels/StyledComponents.js'

const PageCover = (currentCover, updateCover) => {
    //displays current user cover and lets them upload a new cover
    //on accepting file input, calls coverModal to handle further customization
    return (
        <CoverContainer>
            {currentCover && <img src={apiDomain + currentCover} alt = '' style= {{width:"100%", height:"100%", objectFit : "cover" }}/>}
            <input accept="image/*" style = {{display:"none"}} id="icon-button-file" type="file" onChange={(e) => updateCover(e)}/>
            <label htmlFor="icon-button-file">
                <Tooltip title={<span style={{fontSize:"14px", overflow:"hidden", transition:"all .5s ease"}}>ALTERAR CAPA</span>} placement="left">
                    <IconButton style={{position:"absolute",right:"0",top:"0",color:"#fff"}}color="primary" aria-label="upload picture" component="span">
                        <PhotoCamera />
                    </IconButton>
                </Tooltip>
            </label>
        </CoverContainer>
    )
}

const ProfileAvatar = (currentAvatar, hoverTrue, handleHoverAlterarFoto, modalControl) => {
    //display current user avatar and lets them upload a new one
    //on click, calls AvatarModal to handle file selection
    return (
        <ProfileAvatarDiv onMouseEnter={handleHoverAlterarFoto} onMouseLeave={handleHoverAlterarFoto} onClick={modalControl}>
            <img src={currentAvatar ? apiDomain + currentAvatar : noAvatar} alt = "user avatar" style={{height : "inherit", width : "inherit", border:"0", verticalAlign:"middle"}}/>
            <ChangeAvatarDiv  style={ {display : hoverTrue ? 'flex' : 'none'}}>
                <span>Alterar Foto</span>
            </ChangeAvatarDiv>
        </ProfileAvatarDiv>
    )
}

const UserProfileInfo = (user, education) => {
    return (
        <UserProfileInfoDiv>
            <p style={{fontSize:"28px", color:"#fff", paddingTop:"5px", paddingBottom:"5px", fontWeight:"500", backgroundColor:"#77777796", borderRadius : "5px"}}>{user}</p>
            <div style={{fontSize:"14px", color:"#fff", marginBottom:"2px"}}>
                <p>{education}</p>
            </div>
        </UserProfileInfoDiv>
    )
}

const EditProfileButton = () => {
    const {state} = React.useContext(Store)
    return (
        <EditProfileAnchor to="/editarperfil">
            <Button>
                {state.windowSize.width >=900 ?
                    (
                        <React.Fragment>
                            <EditIcon style={{marginRight:"5px", verticalAlign:"middle"}}/> <span>EDITAR PERFIL</span>
                        </React.Fragment>
                    )
                    :
                    (
                        <EditIcon style={{marginRight:"5px", verticalAlign:"middle"}}/>
                    )
                }
            </Button>
        </EditProfileAnchor>
    )
}

const SubmitterStatus = (status) => {
    let text;
    switch (status) {
        case 'requested':
            text = "Verificando cadastro de professor(a)"
            break;
        case 'accepted':
            text = "Professor(a)"
            break;
        default:
            text = "Você é professor(a) e gostaria de publicar recursos?"
    }

    return (
        <React.Fragment>
            <p style={{fontSize:"15px", lineHeight:"22px", textAlign:"left", margin:"0 0 10px"}}>
                <span style={{cursor:"pointer"}}>
                                <span style={{paddingRight:"5px"}}>
                                    <img src={CheckDecagram}/>
                                </span>
                                {text}
                                <span style={{color:"#00bcd4"}}> SAIBA MAIS</span>
                </span>
            </p>
        </React.Fragment>
    )

}

const GetHeaderConfig = () => {

    let config = {
        headers : {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'Access-Token': sessionStorage.getItem('@portalmec/accessToken'),
            'Client': sessionStorage.getItem('@portalmec/clientToken'),
            'Uid': sessionStorage.getItem('@portalmec/uid'),
        }
    }
    {/*'Host': 'api.portalmec.c3sl.ufpr.br',
    'Cookie': ''*/}
    return config
}

export default function UserPage (props){
    const {state, dispatch} = useContext(Store)
    const [hoverAlterarFoto, handleAlterarFoto] = React.useState(false)
    const [tabValue, setTabValue] = useState(
        Number(props.location.state) || 0
    );
    const [tabs, setTabs] = useState([
        'Atividades', 'Meus Recursos', 'Favoritos', 'Coleções', 'Rede'
    ])
    {/*sessionStorage.getItem('@portalmec/username')*/}
    const user = state.currentUser.username
    {/*sessionStorage.getItem('@portalmec/id')*/}
    const id = state.currentUser.id
    const [modalOpen, handleModal] = useState(false)
    const [coverImg, setCoverImg] = useState(state.currentUser.userCover)

    const modalControl = () => {
        handleModal(!modalOpen)
    }

    const handleHoverAlterarFoto = () => {
        handleAlterarFoto(!hoverAlterarFoto)
    }

    useEffect( () => {
        if (id != '') {
        axios.get( (`${apiUrl}/users/` + id), {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'Host': 'api.portalmec.c3sl.ufpr.br',
            'Cookie': ''
        })
        .then( (response) => {
            console.log(response)
                dispatch ({
                    type : 'USER_ACCESSED_USER_PAGE',
                    set: {
                        id : response.data.id,
                        email : response.data.email,
                        username : response.data.name,
                        accessToken : response.headers['access-token'],
                        clientToken : state.currentUser.clientToken,
                        userAvatar : response.data.avatar,
                        userCover : response.data.cover,
                        followCount : response.data.follow_count,
                        collectionsCount: response.data.collections_count,
                        submitter_request : response.data.submitter_request,
                    }
                })
                if((response.data.role_ids.includes(4))) {
                    setTabs([
                        'Atividades', 'Meus Recursos', 'Favoritos', 'Coleções', 'Rede', 'Curadoria'
                    ])
                }
            },
            (error) => {
                console.log('error while running ComponentDidMout')
            }
        )}
    }, [])

    const redirect = () => {
        props.history.push('/')
    }

    const handleChangeTab = (event, newValue) => {
        setTabValue(newValue)
    }

    const updateCover = (selectorFiles : FileList) => {
        const objectURL = URL.createObjectURL(selectorFiles[0])
        console.log(objectURL)
        //setCoverImg(img)
        //modal selecionar posicao do coverImg


    }

    return (
        <>
        <link href="https://fonts.googleapis.com/css?family=Roboto:100,400,500&display=swap" rel="stylesheet"/>
        {
            state.userIsLoggedIn?
            (
                [
                    <React.Fragment>
                        <ModalAlterarAvatar
                            open={modalOpen}
                            handleClose={modalControl}
                            userAvatar={state.currentUser.userAvatar}
                        />
                    <BackgroundDiv>

                            <CustomizedBreadcrumbs
                                values={["Minha área", tabs[tabValue]]}
                            />
                            <Grid container spacing={2}>
                                <Grid item xs={12}>
                                    <div style={{padding : "10px 0 8px 0"}}>
                                        <UserProfileContainer>
                                            <HeaderContainer>
                                                {PageCover(state.currentUser.userCover, (e) => updateCover(e.target.files))}

                                                {ProfileAvatar(state.currentUser.userAvatar, hoverAlterarFoto, handleHoverAlterarFoto, modalControl)}

                                                {UserProfileInfo(user, state.currentUser.education)}

                                                {EditProfileButton()}
                                            </HeaderContainer>

                                            <CheckTeacherDiv>
                                                {SubmitterStatus(state.currentUser.submitter_request)}
                                            </CheckTeacherDiv>

                                            <RodapeDiv>
                                                <NavBarContentContainer>
                                                    <StyledTabs
                                                        value ={tabValue}
                                                        onChange ={handleChangeTab}
                                                        indicatorColor ="primary"
                                                        textColor ="primary"
                                                        variant = "scrollable"
                                                        scrollButtons = "auto"
                                                        TabIndicatorProps={{style : {background:"#00bcd4"}}}
                                                    >
                                                        {
                                                            tabs.map( (tab) =>
                                                                <StyledTab label ={tab} key={tab}/>
                                                            )
                                                        }

                                                    </StyledTabs>
                                                </NavBarContentContainer>
                                            </RodapeDiv>
                                        </UserProfileContainer>
                                    </div>
                                </Grid>

                                <Grid item xs={12}>
                                    {tabValue === 0 &&
                                        <TabPanelAtividades id={id} config={GetHeaderConfig()}/>}
                                    {tabValue === 1 &&
                                        <TabPanelMeusRecursos id={id} config={GetHeaderConfig()}/>}
                                    {tabValue === 2 &&
                                        <TabPanelFavoritos id={id} config={GetHeaderConfig()}/>}
                                    {tabValue === 3 &&
                                        <TabPanelColecoes id={id} config={GetHeaderConfig()}/>}
                                    {tabValue === 4 &&
                                        <TabPanelRede id={id} config={GetHeaderConfig()}/>}
                                    {tabValue === 5 &&
                                        <TabPanelCuradoria id={id} config={GetHeaderConfig()}/>}
                                </Grid>
                            </Grid>
                        </BackgroundDiv>
                    </React.Fragment>
                ]
            )
            : (
                <>
                {redirect()}
                </>
            )
        }
        </>

      )

  }


const ProfileAvatarDiv = styled.div`
    bottom : -65px;
    left : 60px;
    border-radius : 100%;
    position : absolute;
    width : 150px;
    height : 150px;
    overflow : hidden;
    border : 8px solid #fff;
    outline : 0;
    cursor : pointer;
    background-color : #a5a5a5;
`

export const ChangeAvatarDiv = styled.div`
  height : 40px;
  position: absolute;
  width : 100%;
  bottom : 0;
  display : flex;
  background-color : #000;
  color : #fff;
  justify-content : center;
`


const EditProfileAnchor = styled(Link)`
  Button {
      box-shadow : 0 2px 5px 0 rgba(0,0,0,.26);
      background-color : #fafafa;
      position : absolute;
      right : 5px;
      bottom : 0;
      margin-bottom : 20px;
      color : #666;
      padding : 0 10px;
      text-decoration : none;
      border-radius : 3px;
      @media screen and (min-width: 800px) {
          min-height : 36px;
          min-width : 88px;
      }
      line-height : 36px;
      border : 0;
      display: inline-block;
      text-align : center;
      :hover{
        background-color : #fafafa;
      }
      @media screen and (max-width: 600px) {
          max-width : 44px !important ;
      }
  }
`


const StyledTab = styled(Tab)`
    .Mui-selected {
        border-bottom-color : #00bcd4 !important;
    }
    .MuiTab-wrapper {
        border-bottom-color : #00bcd4 !important;
    }
`