import { uniqueId } from 'lodash-es';
import ContentCopyIcon from '@material-hu/icons/material/ContentCopy';
import DeleteOutlineIcon from '@material-hu/icons/material/DeleteOutline';
import KeyboardArrowDownIcon from '@material-hu/icons/material/KeyboardArrowDown';
import KeyboardArrowUpIcon from '@material-hu/icons/material/KeyboardArrowUp';
import {
  Box,
  Card,
  IconButton,
  Stack,
  Tooltip,
  Typography,
} from '@material-hu/mui';

import { type ReviewQuestion, ReviewQuestionType } from 'src/types/performance';
import { useLokaliseTranslation } from 'src/utils/i18n';

import ReviewQuestionLabelStatus from 'src/components/ReviewQuestionLabelStatus';
import RichText from 'src/components/RichText';

import OptionBullet from '../../../Questions/components/OptionBullet';
import QuestionEdition from '../../QuestionEdition';

type PossibleAnswer = {
  id: string | number;
  value: string;
};

type QuestionTemplate = Omit<
  ReviewQuestion,
  'possibleAnswers' | 'commentableStatus'
> & {
  new?: boolean;
  hasAnswer?: boolean;
  hasComment?: boolean;
  commentRequired?: boolean;
  possibleAnswers: PossibleAnswer[];
};

type QuestionTemplatesProps = {
  questionTemplates: QuestionTemplate[];
  move: (from: number, to: number) => void;
  remove: (index: number) => void;
  insert: (index: number, value: QuestionTemplate) => void;
  notIncludingIds: number[];
  setNotIncludingIds: (ids: number[]) => void;
  activeQuestionId: number | null;
  setActiveQuestionId: (id: number | null) => void;
  isTemplateInUse?: boolean;
};

const QuestionTemplates = ({
  questionTemplates,
  move,
  remove,
  insert,
  notIncludingIds,
  setNotIncludingIds,
  activeQuestionId,
  setActiveQuestionId,
  isTemplateInUse,
}: QuestionTemplatesProps) => {
  const { t } = useLokaliseTranslation(['performance', 'general']);

  const handleQuestionClick = (e: React.MouseEvent, questionId: number) => {
    e.stopPropagation();
    setActiveQuestionId(activeQuestionId === questionId ? null : questionId);
  };

  const handleDuplicate = (index: number, question: QuestionTemplate) => {
    insert(index + 1, {
      ...question,
      id: parseInt(uniqueId(), 10),
      new: true,
      possibleAnswers: question.possibleAnswers.map(ans => ({
        value: ans.value,
        id: uniqueId('option_'),
      })),
    });
  };

  const handleRemove = (index: number, questionId: number) => {
    remove(index);
    setNotIncludingIds(notIncludingIds.filter(i => i !== questionId));
    setActiveQuestionId(null);
  };

  if (!questionTemplates?.length) {
    return (
      <Card sx={{ my: 3, p: 4, textAlign: 'center' }}>
        <Typography variant="h6">{t('questions.no_questions')}</Typography>
        <Typography variant="body2">
          {t('questions.no_questions_subtitle')}
        </Typography>
      </Card>
    );
  }

  return (
    <Stack sx={{ mt: 3 }}>
      {questionTemplates?.map((question, index) => (
        <Stack
          key={question.id}
          sx={{
            flexDirection: 'row',
            mt: 2,
            mb: 3,
          }}
        >
          <Stack
            sx={{
              textAlign: 'center',
              mr: 3,
              p: 1,
            }}
          >
            <Typography variant="h5">{index + 1}</Typography>
            <IconButton
              onClick={() => move(index, index - 1)}
              disabled={index === 0 || activeQuestionId !== null}
              sx={{ p: 0, mt: 1 }}
            >
              <KeyboardArrowUpIcon fontSize="large" />
            </IconButton>
            <IconButton
              onClick={() => move(index, index + 1)}
              disabled={
                index === (questionTemplates?.length || 1) - 1 ||
                activeQuestionId !== null
              }
              sx={{ p: 0 }}
            >
              <KeyboardArrowDownIcon fontSize="large" />
            </IconButton>
            {activeQuestionId === question.id && (
              <>
                <Tooltip
                  title={t('general:duplicate')}
                  placement="left"
                >
                  <IconButton
                    sx={{ p: 1, mt: 1 }}
                    onClick={() => handleDuplicate(index, question)}
                  >
                    <ContentCopyIcon fontSize="medium" />
                  </IconButton>
                </Tooltip>
                <Tooltip
                  title={t('general:remove')}
                  placement="left"
                >
                  <IconButton
                    sx={{ p: 1 }}
                    onClick={() => handleRemove(index, question.id)}
                  >
                    <DeleteOutlineIcon fontSize="medium" />
                  </IconButton>
                </Tooltip>
              </>
            )}
          </Stack>
          <Box
            sx={{
              borderRadius: '20px',
              border: theme =>
                `1.5px dashed ${
                  activeQuestionId === question.id
                    ? theme.palette.primary.main
                    : 'transparent'
                }`,
              height: 'auto',
              width: '100%',
              pt: 2,
              pb: 3,
              px: 3,
              '&:hover': {
                borderColor:
                  activeQuestionId === null || activeQuestionId !== question.id
                    ? 'gray'
                    : 'transparent',
                cursor:
                  activeQuestionId === null || activeQuestionId !== question.id
                    ? 'pointer'
                    : 'default',
              },
            }}
            onClick={e => handleQuestionClick(e, question.id)}
          >
            <ReviewQuestionLabelStatus status={question.status} />
            {activeQuestionId !== question.id && (
              <>
                <Typography
                  variant="subtitle2"
                  sx={{
                    color: 'black',
                    mt: 2,
                    mb: 1,
                  }}
                >
                  {question.title}
                </Typography>
                <RichText
                  text={question.description}
                  color="text.secondary"
                />
                {ReviewQuestionType.TEXT !== question.type &&
                  question.possibleAnswers.map((option, idx) => (
                    <Stack
                      key={`${question.id}_${option.id}`}
                      sx={{
                        alignItems: 'center',
                        flexDirection: 'row',
                        spacing: 2,
                        my: 2,
                      }}
                    >
                      <OptionBullet
                        index={idx}
                        type={question.type}
                      />
                      <Typography variant="body2">{option.value}</Typography>
                    </Stack>
                  ))}
              </>
            )}
            {activeQuestionId === question.id && (
              <Stack onClick={e => e.stopPropagation()}>
                <QuestionEdition
                  name="questionTemplates"
                  index={index}
                  unfocus={() => setActiveQuestionId(null)}
                  isTemplateInUse={isTemplateInUse}
                />
              </Stack>
            )}
          </Box>
        </Stack>
      ))}
    </Stack>
  );
};

export default QuestionTemplates;
