import { useState } from 'react';
import { useInfiniteQuery } from 'react-query';

import Close from '@material-hu/icons/material/Close';
import * as colors from '@material-hu/mui/colors';
import Drawer from '@material-hu/mui/Drawer';
import IconButton from '@material-hu/mui/IconButton';
import Paper from '@material-hu/mui/Paper';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import { PeopleExperience } from '@material-hu/components/composed-components/peopleExperience';

import { getFavQuestionsStats } from '../services';
import { FavQuestionsStatsResponse, QuestionTemplateType } from '../types';
import { LokaliseTFunction, useLokaliseTranslation } from 'src/utils/i18n';

import { pxKeys } from '../queries';
import { getFavorabilityCountText, safeTextSelectHandler } from '../utils';

import CellMessage from './CellMessage';
import EngagementDashboard from './EngagementDashboard';
import FavBaseTableList from './FavBaseTableList';
import FavDescriptionTitle from './FavDescriptionTitle';
import FavorabilityChart from './FavorabilityChart';

const { LinearProgressWithLabel } = PeopleExperience;

const renderDescriptionColumn = ({
  row,
  t,
}: {
  row: FavQuestionsStatsResponse;
  t: LokaliseTFunction;
}) => {
  return (
    <Stack>
      <Typography variant="body2">{row.title}</Typography>
      <Typography
        variant="body2"
        sx={theme => ({ color: theme.palette.new.text.neutral.lighter })}
      >
        {[
          getFavorabilityCountText({
            t,
            translationKey: 'answer.answer',
            hasPassedThreshold: row.passedThreshold,
            count: row.answersAmount,
          }),
          getFavorabilityCountText({
            t,
            translationKey: 'comment.comment',
            hasPassedThreshold: row.passedThreshold,
            count: row.commentsAmount,
          }),
          row.topic.title,
        ].join(' | ')}
      </Typography>
    </Stack>
  );
};

const renderDistributionColumn = ({
  row,
  t,
}: {
  row: FavQuestionsStatsResponse;
  t: LokaliseTFunction;
}) => {
  if (!row.passedThreshold) {
    return <CellMessage title={t('NOT_ENOUGH_ANSWERS')} />;
  }

  switch (row.type) {
    case QuestionTemplateType.LIKERT: {
      const { metadata } = row;
      return (
        <FavorabilityChart
          positives={metadata?.promoters ?? 0}
          neutrals={metadata?.neutrals ?? 0}
          negatives={metadata?.detractors ?? 0}
        ></FavorabilityChart>
      );
    }
    case QuestionTemplateType.CHECKBOX:
    case QuestionTemplateType.MULTIPLE_CHOICE: {
      const { metadata } = row;
      return (
        <Stack sx={{ alignItems: 'flex-start' }}>
          <LinearProgressWithLabel value={metadata?.rate ?? 0} />
          <Typography
            variant="body2"
            sx={theme => ({
              color: theme.palette.new.text.neutral.lighter,
              width: '100%',
              textAlign: 'left',
            })}
          >
            {metadata?.option}
          </Typography>
        </Stack>
      );
    }
    case QuestionTemplateType.TEXT:
      return <CellMessage title={t('OPEN_COMMENT')} />;
  }
};

type FavQuestionsListProps = {
  surveyId: number;
  dimensionId?: number;
};

const FavQuestionsList = ({ surveyId, dimensionId }: FavQuestionsListProps) => {
  const { t } = useLokaliseTranslation('people_experience');

  const [drawerOpen, setDrawerOpen] = useState(false);
  const [selectedRow, setSelectedRow] = useState<FavQuestionsStatsResponse>();

  const requestParams = {
    surveyId,
    topicId: dimensionId,
  };

  const { data, isLoading, isPreviousData, hasNextPage, fetchNextPage } =
    useInfiniteQuery(
      pxKeys.favQuestionsStats(requestParams),
      ({ pageParam = 0 }) => {
        return getFavQuestionsStats({
          limit: 30,
          page: pageParam,
          ...requestParams,
        });
      },
      {
        keepPreviousData: true,
        getNextPageParam: lastPage => {
          if (lastPage.page === lastPage.totalPages) {
            return undefined;
          }

          return lastPage.page;
        },
      },
    );

  const handleCloseDrawer = () => setDrawerOpen(false);

  const handleClickRow = (row: FavQuestionsStatsResponse) =>
    safeTextSelectHandler(() => {
      setDrawerOpen(true);
      setSelectedRow(row);
    });

  const tableData = data?.pages.flatMap(page => page.items) ?? [];
  const count = data?.pages[0].count;

  return (
    <>
      <FavBaseTableList
        data={tableData}
        hasNextPage={hasNextPage}
        onLoadMore={fetchNextPage}
        isLoading={isLoading}
        isPreviousData={isPreviousData}
        renderDescriptionColumn={row => renderDescriptionColumn({ row, t })}
        renderDistributionColumn={row => renderDistributionColumn({ row, t })}
        descriptionColumnTitle={
          <FavDescriptionTitle
            title={t('question_one')}
            description={t('questions_amount')}
            count={count}
          />
        }
        slotProps={{
          dataRow: row => ({
            onClick: handleClickRow(row),
            'aria-pressed': drawerOpen && selectedRow?.id === row.id,
          }),
          distributionColumn: row => ({
            sx: {
              bgcolor: theme =>
                row.type === QuestionTemplateType.TEXT || !row.passedThreshold
                  ? theme.palette.new.background.layout.default
                  : undefined,
            },
          }),
        }}
      />
      <Drawer
        open={drawerOpen}
        onClose={handleCloseDrawer}
        anchor="right"
        PaperProps={{
          sx: {
            width: '80%',
            maxWidth: 1400,
            borderTopLeftRadius: theme => theme.spacing(2),
          },
        }}
      >
        <Paper
          component={Stack}
          sx={{
            justifyContent: 'space-between',
            alignItems: 'center',
            gap: 2,
            p: 2,
            flexDirection: 'row',
            position: 'sticky',
            top: 0,
            zIndex: 1,
            borderTopLeftRadius: theme => theme.spacing(2),
          }}
          square
        >
          <Typography variant="h6">{t('QUESTION_DETAIL')}</Typography>
          <IconButton
            aria-label={t('general:close')}
            onClick={handleCloseDrawer}
          >
            <Close />
          </IconButton>
        </Paper>
        {selectedRow && (
          <Stack sx={{ p: 2, gap: 2 }}>
            <Stack
              sx={{
                p: 2,
                alignItems: 'flex-start',
                bgcolor: theme => theme.palette.new.background.layout.default,
                borderRadius: 1,
              }}
            >
              <Typography
                variant="body2"
                sx={theme => ({
                  color: theme.palette.new.text.neutral.lighter,
                })}
              >
                {selectedRow.topic.title}
              </Typography>
              <Typography variant="body1">{selectedRow.title}</Typography>
            </Stack>
            <EngagementDashboard
              question={{
                id: selectedRow.id,
                type: selectedRow.type,
              }}
              surveyId={surveyId}
            />
          </Stack>
        )}
      </Drawer>
    </>
  );
};

export default FavQuestionsList;
