// @ts-nocheck -- TODO: fix remaining type errors in this file
import { useId, useState } from 'react';
import { useQuery } from 'react-query';
import { useParams } from 'react-router-dom';

import { range } from 'lodash-es';
import { useServerPagination } from '@material-hu/hooks/useServerPagination';
import ExpandLess from '@material-hu/icons/material/ExpandLess';
import ExpandMore from '@material-hu/icons/material/ExpandMore';
import MoodBad from '@material-hu/icons/material/MoodBad';
import SentimentNeutralOutlined from '@material-hu/icons/material/SentimentNeutralOutlined';
import SentimentVerySatisfied from '@material-hu/icons/material/SentimentVerySatisfied';
import Box from '@material-hu/mui/Box';
import CircularProgress from '@material-hu/mui/CircularProgress';
import { type Theme, useTheme } from '@material-hu/mui/styles';
import Paper from '@material-hu/mui/Paper';
import Stack from '@material-hu/mui/Stack';
import Table from '@material-hu/mui/Table';
import TableBody from '@material-hu/mui/TableBody';
import TableCell from '@material-hu/mui/TableCell';
import TableContainer from '@material-hu/mui/TableContainer';
import TableHead from '@material-hu/mui/TableHead';
import TableRow from '@material-hu/mui/TableRow';
import Typography from '@material-hu/mui/Typography';

import { PeopleExperience } from '@material-hu/components/composed-components/peopleExperience';
import Button from '@material-hu/components/design-system/Buttons/Button';

import { getManagerSurveyDetail, getQuestionAnswers } from '../services';
import { type QuestionAnswersParams, QuestionTemplateType } from '../types';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { pxKeys } from '../queries';

import EmptyState from './EmptyState';

const { ActionsMenu, ActionsMenuItem } = PeopleExperience;

enum ScoreType {
  PROMOTERS,
  NEUTRAL,
  DETRACTORS,
}

type ScoreTypeOption = {
  label: string;
  value: ScoreType;
};

const getScoreColor = (score: number) => {
  if (score > 8) return 'success.main';
  if (score > 6) return 'warning.main';
  return 'error.main';
};

const getScoreColors = (theme: Theme) => ({
  promoters: {
    color: theme.palette.new.text.feedback.success,
    bgcolor: theme.palette.new.background.feedback.success,
  },
  neutral: {
    color: theme.palette.new.text.feedback.warning,
    bgcolor: theme.palette.new.background.feedback.warning,
  },
  detractors: {
    color: theme.palette.new.text.feedback.error,
    bgcolor: theme.palette.new.background.feedback.error,
  },
});

const getScoreTypeMeta = (theme: Theme, scoreType: ScoreTypeOption) => {
  const scoreColors = getScoreColors(theme);
  switch (scoreType.value) {
    case ScoreType.NEUTRAL:
      return {
        color: scoreColors.neutral.color,
        icon: (
          <SentimentNeutralOutlined sx={{ color: scoreColors.neutral.color }} />
        ),
        bgcolor: scoreColors.neutral.bgcolor,
        filter: [7, 8],
      };
    case ScoreType.DETRACTORS:
      return {
        color: scoreColors.detractors.color,
        icon: <MoodBad sx={{ color: scoreColors.detractors.color }} />,
        bgcolor: scoreColors.detractors.bgcolor,
        filter: range(1, 7),
      };
    case ScoreType.PROMOTERS:
    default:
      return {
        color: scoreColors.promoters.color,
        icon: (
          <SentimentVerySatisfied sx={{ color: scoreColors.promoters.color }} />
        ),
        bgcolor: scoreColors.promoters.bgcolor,
        filter: [9, 10],
      };
  }
};

const EnpsCommentList = () => {
  const { t } = useLokaliseTranslation('people_experience');
  const urlParams = useParams();
  const id = useId();

  const scoreTypeOptions: ScoreTypeOption[] = [
    {
      label: t('PROMOTERS'),
      value: ScoreType.PROMOTERS,
    },
    {
      label: t('NEUTRAL'),
      value: ScoreType.NEUTRAL,
    },
    {
      label: t('DETRACTORS'),
      value: ScoreType.DETRACTORS,
    },
  ];

  const [scoreType, setScoreType] = useState<ScoreTypeOption>(
    scoreTypeOptions[0],
  );

  const { paginationController, pagination } = useServerPagination({
    labelRowsPerPage: t('ROWS_PER_PAGE'),
  });

  const surveyId = Number(urlParams.id);
  const theme = useTheme();
  const { color, icon, bgcolor, filter } = getScoreTypeMeta(theme, scoreType);

  const { data: surveyData } = useQuery(
    pxKeys.surveyDetail(surveyId),
    () => getManagerSurveyDetail(surveyId),
    {
      select: response => response.data,
    },
  );

  const questionId =
    surveyData?.templates?.[0]?.formTemplate?.questionTemplates?.find(
      question => question.type === QuestionTemplateType.NPS,
    )?.id;

  const params: QuestionAnswersParams = {
    formId: surveyId,
    questionId,
    isHighlighted: undefined,
    hasComment: true,
    page: pagination.page + 1,
    limit: pagination.limit,
    integerAnswer: filter,
  };

  const { data, isLoading, isPreviousData } = useQuery(
    pxKeys.questionAnswers(params),
    () => getQuestionAnswers(params),
    { select: res => res.data, enabled: !!questionId, keepPreviousData: true },
  );

  const hasDisplayData = data?.passedThreshold && data?.count;

  return (
    <Stack sx={{ gap: 3, height: '100%' }}>
      <Stack
        sx={{
          flexDirection: 'row',
          p: 2,
          gap: 1,
          bgcolor: theme => theme.palette.new.background.layout.default,
          alignItems: 'center',
        }}
      >
        <Typography
          component="label"
          variant="h6"
          htmlFor={id}
        >
          {t('VIEW_BY')}
        </Typography>
        <ActionsMenu
          renderTrigger={({ ariaProps, open, handleOpen }) => (
            <Button
              {...ariaProps}
              variant="text"
              onClick={handleOpen}
              endIcon={open ? <ExpandLess /> : <ExpandMore />}
            >
              {scoreType.label}
            </Button>
          )}
          closeOnSelect
        >
          {scoreTypeOptions.map(option => (
            <ActionsMenuItem
              key={option.value}
              onClick={() => setScoreType(option)}
            >
              {option.label}
            </ActionsMenuItem>
          ))}
        </ActionsMenu>
      </Stack>
      <TableContainer
        component={Paper}
        elevation={2}
      >
        {isLoading && (
          <Stack sx={{ alignItems: 'center', p: 4, width: '100%' }}>
            <CircularProgress />
          </Stack>
        )}
        {!isLoading && (
          <Table
            sx={{
              minWidth: 650,
              tableLayout: 'auto',
              opacity: isPreviousData ? 0.5 : 1,
            }}
          >
            <TableHead>
              <TableRow>
                <TableCell sx={{ width: 88 }}>{t('SCORE')}</TableCell>
                <TableCell>{t('comment.comments')}</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {hasDisplayData && (
                <TableRow sx={{ bgcolor }}>
                  <TableCell>{icon}</TableCell>
                  <TableCell>
                    <Typography
                      variant="subtitle2"
                      sx={{ color }}
                    >
                      {scoreType.label}
                    </Typography>
                    <Typography
                      variant="caption"
                      sx={{ color }}
                    >
                      {t('comment_count', { count: data?.count })}
                    </Typography>
                  </TableCell>
                </TableRow>
              )}
              {!hasDisplayData && (
                <TableRow>
                  <TableCell colSpan={2}>
                    <EmptyState
                      title={t('NOT_ENOUGH_DATA_TITLE')}
                      description={t('NOT_ENOUGH_DATA_DESCRIPTION')}
                    />
                  </TableCell>
                </TableRow>
              )}
              {data?.items?.map(answer => {
                const score = answer.answer.integer;
                return (
                  <TableRow key={answer.id}>
                    <TableCell>
                      <Typography
                        variant="body2"
                        sx={{
                          color: getScoreColor(score ?? 0),
                          fontWeight: 'fontWeightMedium',
                        }}
                      >
                        {score}
                      </Typography>
                    </TableCell>
                    <TableCell sx={{ whiteSpace: 'unset' }}>
                      <Typography
                        variant="body2"
                        sx={{ whiteSpace: 'inherit' }}
                      >
                        &quot;{answer.comment}&quot;
                      </Typography>
                    </TableCell>
                  </TableRow>
                );
              })}
            </TableBody>
          </Table>
        )}
        <Box sx={{ py: 1 }}>{paginationController(data?.count ?? 0)}</Box>
      </TableContainer>
    </Stack>
  );
};

export default EnpsCommentList;
