/*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, { useEffect, useState, useContext } from 'react'
import { Store } from '../Store'
import styled from 'styled-components'
import { apiDomain } from '../env';
import CustomizedBreadcrumbs from '../Components/TabPanels/Breadcrumbs.js'
import Grid from '@material-ui/core/Grid';
import FollowButton from '../Components/ContactButtons/FollowButton.js'
import FollowingButton from '../Components/ContactButtons/FollowingButton.js'
import FollowersCountButton from '../Components/ContactButtons/FollowersCountButton.js'
import noAvatar from "../img/default_profile.png";
import Tab from '@material-ui/core/Tab';
import TabInicio from '../Components/TabPanels/PublicUserPageTabs/TabInicio.js'
import TabRecursos from '../Components/TabPanels/PublicUserPageTabs/TabRecursos.js'
import TabColecoes from '../Components/TabPanels/PublicUserPageTabs/TabColecoes.js'
import TabRede from '../Components/TabPanels/PublicUserPageTabs/TabRede.js'
import CheckDecagram from '../img/check-decagram-blue.svg'
import ReportButton from '../Components/ReportButton.js'
import { HeaderContainer, UserProfileContainer, CoverContainer, UserProfileInfoDiv, StyledTabs, CheckTeacherDiv, RodapeDiv, NavBarContentContainer, BackgroundDiv } from '../Components/TabPanels/StyledComponents.js'
import { fetchAllRequest } from '../Components/HelperFunctions/getAxiosConfig'
import Typography from '@material-ui/core/Typography';
import CircularProgress from '@material-ui/core/CircularProgress';

function RenderFollowContainer(props) {
  const { state } = useContext(Store) 
  const [followed, setFollowed] = useState(props.followed)
  const toggleFollowed = () => { setFollowed(!followed) }

  return (
    <FollowContainer>
      <>
        {
          (props.id !== state.currentUser.id) &&
            followed ?
            (
              <FollowingButton followedID={props.id} toggleFollowed={toggleFollowed} />
            )
            :
            (
              <FollowButton followerID={props.id} toggleFollowed={toggleFollowed} />
            )
        }
        <FollowersCountButton followCount={props.followCount} />
      </>
    </FollowContainer>
  )
}

const RenderProfileAvatar = (userAvatar) => {
  return (
    <ProfileAvatarDiv>
      <img src={userAvatar ? apiDomain + userAvatar : noAvatar} alt="user avatar" style={{ height: "inherit", width: "inherit", border: "0", verticalAlign: "middle" }} />
    </ProfileAvatarDiv>
  )
}

const RenderUserProfileInfo = (userName) => {
  return (
    <UserProfileInfoDiv>
      <p
        style={{ fontSize: "28px", color: "#fff", marginBottom: "2px", fontWeight: "500", borderRadius: "5px", textShadow: "0 1px 2px rgba(0,0,0,.45)" }}
      >
        {userName}
      </p>
    </UserProfileInfoDiv>
  )
}

const RenderCheckTeacher = (submitter_request) => {
  if (submitter_request === "accepted") {
    return (
      <CheckTeacherDiv>
        <p>
          <span>
            <img alt="" src={CheckDecagram} />
          </span>
                    Professor(a)
                </p>
      </CheckTeacherDiv>
    )
  }
}

export default function PublicUserPage(props) {
  /*currentUser info variables--------------------------------------*/
  const { state } = useContext(Store)
  /*user info variables--------------------------------------*/
  const WIDTH = window.innerWidth;
  const [id, setId] = useState(props.match.params.userId)

  const [loading, setLoading] = useState(false);

  const [userData, setUserData] = useState({})
  const fillUserInfo = (data) => {
    setUserData(data)
  }
  /*---------------------------------------------------------*/
  const [following, setFollowing] = useState(0);
  const fillFollowing = (data) => {
    if (data.errors)
      setFollowing('Você precisa logar para ver o que usuário está ');
    else
      setFollowing(data.length);
  }

  /*content control variables--------------------------------*/
  // eslint-disable-next-line
  const [tabs, setTabs] = useState([
    'Início', 'Recursos', 'Coleções', 'Rede'
  ])
  const [tabValue, setTabValue] = useState(0);
  const handleChangeTab = (event, newValue) => {
    setTabValue(newValue)
  }
  /*---------------------------------------------------------*/

  /*content variables--------------------------------*/
  const [learningObjArr, setLearningObjects] = useState([])
  const handleLearningObjects = (data) => { setLearningObjects(data) }
  const [collectionsArr, setCollections] = useState([])
  const handleCollections = (data) => { setCollections(data) }
  /*---------------------------------------------------------*/

  function handleSuccess(responseArr) {
    fillUserInfo(responseArr[0])

    handleLearningObjects(responseArr[1])

    handleCollections(responseArr[2])

    fillFollowing(responseArr[3]);
    setLoading(false);
  }

  /*Component Will Mount*/
  useEffect(() => {
    const id = props.match.params.userId
    setId(id)
    const urls = [`/users/${id}`, `/users/${id}/learning_objects`, `/users/${id}/collections`, `/users/${id}/following/User`]
    setLoading(true);
    fetchAllRequest(urls, handleSuccess, (error) => { console.log(error) })
  }, [state.currentUser.id, props.match.params.userId])
  /*---------------------------------------------------------*/

  return (
    <React.Fragment>
      <link href="https://fonts.googleapis.com/css?family=Roboto:100,400,500&display=swap" rel="stylesheet" />
      <BackgroundDiv>
        <CustomizedBreadcrumbs
          values={["Usuário Público", tabs[tabValue]]}
        />
        <Grid container spacing={2}>
          <Grid item xs={12}>
            <div style={{ padding: "10px 0 8px 0" }}>
              <UserProfileContainer>
                <HeaderContainer>
                  <>
                    {!loading && <RenderFollowContainer followed={userData.followed} id={id} followCount={userData.follows_count} />}
                    {RenderProfileAvatar(userData.avatar ? userData.avatar : undefined)}
                    <CoverContainer>
                      {userData.cover && <img src={apiDomain + userData.cover} alt='' style={{ width: "100%", height: "100%", objectFit: "cover" }} />}
                    </CoverContainer>
                    {
                      WIDTH <= 501 ? null : RenderUserProfileInfo(userData.name)
                    }
                  </>
                </HeaderContainer>
                {
                  WIDTH <= 501 ?
                    <Grid style={{ marginTop: '4em' }} container justify="center" alignItems="center" direction="column">
                      <Grid item>
                        <Typography variant="h4" gutterBottom style={{ textAlign: "center" }}>
                          {
                            userData.name
                          }
                        </Typography>
                      </Grid>
                      <Grid style={{ marginTop: '0.5em', marginBottom: '0.5em', borderTop: "0.5px solid #DCDCDC", borderBottom: "0.5px solid #DCDCDC" }} container spacing={4} justify="center" alignItems="center" direction="row">
                        <Grid item>
                          <Typography variant="h6" style={{ textAlign: 'center' }}>
                            {
                              loading ?
                                <CircularProgress size={20} /> :
                                `${userData.follows_count} seguidores`
                            }
                          </Typography>
                        </Grid>
                        <Grid item>
                          <Typography variant="h6" style={{ textAlign: 'center' }} >
                            {
                              loading ?
                                <CircularProgress size={20} /> :
                                `${following} seguindo`
                            }
                          </Typography>
                        </Grid>
                      </Grid>
                    </Grid>
                    :
                    RenderCheckTeacher(userData.submitter_request)}
                <RodapeDiv>
                  <NavBarContentContainer>
                    <StyledTabs
                      value={tabValue}
                      onChange={handleChangeTab}
                      indicatorColor="primary"
                      textColor="primary"
                      variant="scrollable"
                      scrollButtons="desktop"
                      TabIndicatorProps={{ style: { background: "#00bcd4" } }}
                    >
                      {
                        tabs.map((tab) =>
                          <Tab label={tab} key={tab}
                            disabled={(tab === "Recursos" && learningObjArr.length === 0) || (tab === "Coleções" && collectionsArr.length === 0) || (tab === "Rede" && state.currentUser.id === '')}
                          />
                        )
                      }
                    </StyledTabs>
                  </NavBarContentContainer>
                  <ReportButton className="report-button" complainableId={userData.id} complainableType={"User"} />
                </RodapeDiv>
              </UserProfileContainer>
            </div>
          </Grid>

          {
            !loading &&
            <Grid item xs={12}>
              {tabValue === 0 &&
                <TabInicio id={id} user={userData} learningObjs={learningObjArr} collections={collectionsArr} />}
              {tabValue === 1 &&
                <TabRecursos count={userData.learning_objects_count} learningObjs={learningObjArr} id={id} />}
              {tabValue === 2 &&
                <TabColecoes id={id} username={userData.name} />}
              {tabValue === 3 &&
                <TabRede id={id} username={userData.name} />}
            </Grid>
          }
        </Grid>
      </BackgroundDiv>
    </React.Fragment>
  )
}


const ProfileAvatarDiv = styled.div`
    overflow : hidden;
    border-radius : 100%;
    bottom : -10px;
    left : 20px;
    z-index : 10;
    box-sizing : content-box;
    position : absolute;
    width : 150px;
    height : 150px;
    border : 4px solid #fff;
    outline : 0;
    background-color : #fff;
    @media screen and (max-width: 501px) {
            height : 73px;
            width : 73px;
            position:absolute;
            left:0;
            right:0;
            bottom : -40px;
            margin-left:auto;
            margin-right:auto;
        }
`


const FollowContainer = styled.div`
    padding : 4px 10px;
    right : 0;
    position : absolute;
    z-index : 1;
`