import { useQuery } from 'react-query';

import { useModal } from '@material-hu/hooks/useModal';
import { useServerPagination } from '@material-hu/hooks/useServerPagination';
import DownloadIcon from '@material-hu/icons/material/Download';
import Card from '@material-hu/mui/Card';
import CardContent from '@material-hu/mui/CardContent';
import Container from '@material-hu/mui/Container';
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 TableHead from '@material-hu/mui/TableHead';
import TableRow from '@material-hu/mui/TableRow';
import Typography from '@material-hu/mui/Typography';

import IconsMenu from '@material-hu/components/deprecated/IconsMenu';
import Title from '@material-hu/components/design-system/Title';

import useHuGoTheme from 'src/hooks/useHuGoTheme';
import useRequiredParams from 'src/hooks/useRequiredParams';
import EyeIcon from 'src/icons/Eye';
import AnswerPopup from 'src/pages/dashboard/Forms/Forms/components/AnswerPopup';
import * as formsService from 'src/services/formsService';
import * as usersService from 'src/services/usersService';
import { FormTypes } from 'src/types/form';
import { download } from 'src/utils/filesUtils';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { formatUTCDate } from 'src/utils/timeUtils';

import CircularProgress from 'src/components/CircularProgress';
import DownloadingModal from 'src/components/DownloadingModal';
import FormApprovalStatus from 'src/components/FormApprovalStatus';
import Scrollbar from 'src/components/Scrollbar';
import ThemeWrapper from 'src/components/ThemeWrapper';

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

const FormsTab = () => {
  const { t } = useLokaliseTranslation(['users', 'backoffice_only']);
  const { id } = useRequiredParams(['id']);
  const userId = Number(id);

  const {
    query,
    pagination,
    Searchbar,
    paginationController,
    orderBy,
    order,
    TableSortingHeader,
  } = useServerPagination({
    labelRowsPerPage: t('GENERAL:ROWS_PER_PAGE'),
  });

  const params = {
    title: query,
    ...pagination,
    orderBy,
    order,
    type: FormTypes.FORM,
  };

  const {
    data: answers,
    isLoading,
    refetch,
  } = useQuery(
    usersKeys.userForms(userId, params),
    () => usersService.getUserForms(userId, params),
    {
      keepPreviousData: true,
      select: response => response.data,
    },
  );

  const {
    modal: downloadingModal,
    showModal: showDownloadingModal,
    closeModal: closeDownloadingModal,
  } = useModal(
    DownloadingModal,
    { maxWidth: 'sm', fullWidth: true },
    { extended: false },
  );

  const handleDownloadAnswers = async (answer: any) => {
    showDownloadingModal();
    const { data: pdf } = await formsService.getFormAnswerPdf(
      answer.templateId,
      answer.id,
    );
    download(pdf, `${answer.title}.pdf`);
    closeDownloadingModal();
  };

  const {
    modal: answerModal,
    showModal: showAnswerModal,
    closeModal: closeAnswerModal,
  } = useModal(AnswerPopup, { fullWidth: true, maxWidth: 'md' });

  const HuGoThemeProvider = useHuGoTheme();

  if (isLoading) {
    return (
      <ThemeWrapper>
        <CircularProgress centered />
      </ThemeWrapper>
    );
  }

  return (
    <Container sx={{ py: 3 }}>
      <Stack sx={{ gap: 2 }}>
        <HuGoThemeProvider>
          <Title
            variant="L"
            title={t('backoffice_only:dashboard_sidebar.forms')}
          />
        </HuGoThemeProvider>
        <ThemeWrapper>
          <Card>
            <Searchbar
              placeholder={t('SEARCH_BY_TITLE')}
              sx={{ p: 1 }}
            />
            {answerModal}
            {downloadingModal}
            {answers?.count ? (
              <>
                <Scrollbar>
                  <Table>
                    <TableHead>
                      <TableRow>
                        <TableSortingHeader id="TITLE">
                          {t('TITLE')}
                        </TableSortingHeader>
                        <TableSortingHeader
                          align="center"
                          id="UPDATED_AT"
                        >
                          {t('DATE')}
                        </TableSortingHeader>
                        <TableSortingHeader
                          align="center"
                          id="APPROVAL_STATUS"
                        >
                          {t('STATUS')}
                        </TableSortingHeader>
                        <TableCell align="center">{t('ACTIONS')}</TableCell>
                      </TableRow>
                    </TableHead>
                    <TableBody>
                      {answers.items.map(answer => (
                        <TableRow
                          hover
                          key={answer.id}
                        >
                          <TableCell>{answer.title}</TableCell>
                          <TableCell
                            align="center"
                            variant="shortField"
                          >
                            {formatUTCDate(answer.createdAt)}
                          </TableCell>
                          <TableCell
                            align="center"
                            variant="shortField"
                          >
                            <FormApprovalStatus
                              status={answer.approvalStatus}
                            />
                          </TableCell>
                          <TableCell
                            align="center"
                            variant="shortField"
                          >
                            <IconsMenu
                              options={[
                                {
                                  onClick: () =>
                                    showAnswerModal({
                                      answerIds: answers.items.map(a => a.id),
                                      answerId: answer.id,
                                      formId: answer.templateId!,
                                      handleClose: closeAnswerModal,
                                      refetchAnswers: refetch,
                                    }),
                                  icon: <EyeIcon fontSize="small" />,
                                  label: t('PREVIEW'),
                                },
                                {
                                  onClick: () => handleDownloadAnswers(answer),
                                  icon: <DownloadIcon fontSize="small" />,
                                  label: t('DOWNLOAD'),
                                },
                              ]}
                            />
                          </TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                </Scrollbar>
                {paginationController(answers.count)}
              </>
            ) : (
              <CardContent>
                <Typography>{t('NO_ANSWERS')}</Typography>
              </CardContent>
            )}
          </Card>
        </ThemeWrapper>
      </Stack>
    </Container>
  );
};

export default FormsTab;
