import { useEffect, useState } from 'react';
import {
  Box,
  Chip,
  Divider,
  Grid,
  Paper,
  Typography
} from '@mui/material';
import {
  Check as CheckIcon,
  Close as CloseIcon,
  Lock as LockIcon,
  PendingOutlined as PendingOutlinedIcon,
  RadioButtonUnchecked as RadioButtonUncheckedIcon,
} from '@mui/icons-material';
import { useApp } from '../app';
import UserAvatar from '../UserAvatar';
import colors from '../theme/colors';
import { learningObjectiveToIcon } from '../utils/learning-objectives';
import WrittenFeedback from './WrittenFeedback';

const intl = {
  es: {
    pending: 'Pendiente',
    yes: 'Si',
    no: 'No',
    bypassed: 'Bypassed',
    'learning-objectives': 'Objetivos de aprendizaje',
  },
  en: {
    pending: 'Pending',
    yes: 'Yes',
    no: 'No',
    bypassed: 'Bypassed',
    'learning-objectives': 'Learning objectives',
  },
  pt: {
    pending: 'Pendente',
    yes: 'Sim',
    no: 'Não',
    bypassed: 'Bypassed',
    'learning-objectives': 'Objetivos de aprendizagem',
  },
};

const StudentProjectResults = ({
  lang,
  project,
  learningObjectives,
  projectAssessments,
  studentProject,
}) => {
  const app = useApp();
  const { user } = app.auth;
  const [peerBypassFound, setPeerBypassFound] = useState(false);
  const combinedLearningObjectives = project.getCombinedLearningObjectives(studentProject.projectVariant);
  const cats = combinedLearningObjectives.reduce(
    (memo, { id }) => {
      const cat = id.split('/').shift();
      if (memo.includes(cat)) {
        return memo;
      }
      return [...memo, cat];
    },
    [],
  );

  const lastAssessmentsByType = projectAssessments.reduce(
    (memo, projectAssessment) => (
      !memo[projectAssessment.data.type] || projectAssessment.createdAt > memo[projectAssessment.data.type].createdAt
        ? { ...memo, [projectAssessment.data.type]: projectAssessment }
        : memo
    ),
    {},
  );

  useEffect(() => {
    if (!lastAssessmentsByType.self) {
      return;
    }

    app.activityLogEntry.findMany({
      where: {
        uid: lastAssessmentsByType.self.uid,
        type: 'project_assessment_bypass',
        path: `${lastAssessmentsByType.self.data.slug}/peer`,
        data: {
          path: ['studentProjectId'],
          equals: lastAssessmentsByType.self.data.studentProjectId,
        },
      }
    })
      .then(res => {
        if (res.length > 0) {
          setPeerBypassFound(true);
        }
      })
      .catch(err => {
        console.log(err);
      });

  }, [app, lastAssessmentsByType]);

  // Si es que no hay assessment de peer, pero sí de coach, entonces
  // quiere decir que su peer assessment fue bypasseado
  if (peerBypassFound) {
    lastAssessmentsByType.peer = 'bypassed';
  }

  // En admin solo hay inglés (en) mientras que en bootcamp hay es y pt
  const fallbackLang = lang === 'pt' ? 'pt' : 'es';
  const perceptions = ['Alert', 'Ok', 'Outstanding'];

  return (
    <Paper variant="padded">
      <Grid container>
        {user.isStaff && (
          <>
            <Grid item xs={12} sm={9}>
              <Typography variant="h3">
                Evaluación de
              </Typography>
              <Grid container sx={{ mb: 3 }}>
                <Grid item xs={4} sm={3} md={2}>
                  <UserAvatar user={lastAssessmentsByType.self.author} size="md" />
                </Grid>
                <Grid item xs={8} sm={9} md={10} sx={{ position: 'relative' }}>
                  <Typography variant="h4">
                    {lastAssessmentsByType.self.author.firstName}
                  </Typography>
                </Grid>
              </Grid>
            </Grid>
            <Grid item xs={12} sm={9}>
              <Grid container sx={{ mb: 3 }}>
                <Grid item xs={8} sm={3} md={12}>
                  <Typography variant="h3">
                    Para el proyecto {project.intl[fallbackLang].title}
                  </Typography>
                </Grid>
              </Grid>
            </Grid>
          </>
        )}
        <Grid item xs={12}>
          <WrittenFeedback lang={lang} projectAssessments={projectAssessments} />
        </Grid>
      </Grid>
      {user.isStaff && (
        <Grid container sx={theme => ({
          mt: theme.spacing(3),
          mr: theme.spacing(-1),
          mb: theme.spacing(3),
          p: theme.spacing(3),
          backgroundColor: theme.palette.grey[300],
          direction: "row",
          alignItems: "center"
        })}>
          <Grid item sx={{ m: 1 }}>
            <LockIcon />
          </Grid>
          <Grid item>
            <Typography variant="h4">
              Comentario de seguimiento para el equipo
            </Typography>
          </Grid>
          <Grid item md={12} sx={{ m: 1 }}>
            <Typography variant="body1">
              {lastAssessmentsByType.coach.data.privateComments}
            </Typography>
          </Grid>
          <Divider style={{ width: '100%', border: '1px solid' }} />
          <Grid item md={12} sx={{ m: 1 }}>
            <Typography variant="body1">
              {`Percepción de ${lastAssessmentsByType.coach.author.firstName}:
                  ${perceptions[lastAssessmentsByType.coach.data.perception]}`}
            </Typography>
          </Grid>
        </Grid>
      )}
      <Grid container>
        <Grid item xs={12} sm={9}>
          <Typography variant="h2">
            {intl[fallbackLang]['learning-objectives']}
          </Typography>
        </Grid>
        <Grid item xs={4} sm={1} sx={{ textAlign: 'center' }}>self</Grid>
        <Grid item xs={4} sm={1} sx={{ textAlign: 'center' }}>peer</Grid>
        <Grid item xs={4} sm={1} sx={{ textAlign: 'center' }}>coach</Grid>
      </Grid>
      {cats.map((cat) => {
        const subcats = combinedLearningObjectives.reduce(
          (memo, lo) => (
            !lo.id.startsWith(`${cat}/`)
              ? memo
              : [...memo, lo]
          ),
          [],
        );
        const icon = learningObjectiveToIcon(cat);
        return (
          <Box key={cat} sx={{ mb: 3 }}>
            <Typography key={cat} variant="h3">
              {icon.build({ marginRight: 8 })}
              {learningObjectives.intl[fallbackLang][cat]?.title || cat}
            </Typography>
            {subcats.map((subcat) => {
              return (
                <Grid key={subcat.id} container>
                  <Grid item xs={12} sm={9}>
                    <Typography
                      key={subcat.id}
                      variant="body1"
                      component="span"
                      sx={{
                        display: 'inline-block',
                        mb: 2,
                      }}
                    >
                      {learningObjectives.intl[fallbackLang][subcat.id]?.title
                        || subcat.id.split('/').slice(1).join('/')}
                      {subcat.optional && (
                        <Chip
                          sx={{ ml: 1 }}
                          label="Opcional"
                          variant="outlined"
                          color="info"
                          size="small"
                        />
                      )}
                    </Typography>
                  </Grid>
                  {['self', 'peer', 'coach'].map((type) => {
                    const statusIcon = (
                      lastAssessmentsByType[type] === 'bypassed'
                        ? <RadioButtonUncheckedIcon titleAccess={intl[lang].bypassed} sx={{ color: colors.yellow.dark }} />
                        : typeof lastAssessmentsByType[type]?.data?.learningObjectives[subcat.id] === 'undefined'
                          ? <PendingOutlinedIcon titleAccess={intl[lang].pending} />
                          : lastAssessmentsByType[type].data.learningObjectives[subcat.id]
                            ? <CheckIcon titleAccess={intl[lang].yes} sx={{ color: colors.mint.dark }} />
                            : <CloseIcon titleAccess={intl[lang].no} sx={{ color: colors.error.main }} />
                    );
                    return (
                      <Grid key={type} item xs={4} sm={1} sx={{ textAlign: 'center' }}>
                        {statusIcon}
                      </Grid>
                    );
                  })}
                </Grid>
              );
            })}
          </Box>
        );
      })}
    </Paper>
  );
};

export default StudentProjectResults;
