import { FC, useState } from 'react';
import { Helmet } from 'react-helmet-async';
import { useInfiniteQuery, useMutation } from 'react-query';
import { useNavigate } from 'react-router-dom';

import { useModal } from '@material-hu/hooks/useModal';
import { IconPlus } from '@material-hu/icons/tabler';
import CircularProgress from '@material-hu/mui/CircularProgress';
import Stack from '@material-hu/mui/Stack';

import Button from '@material-hu/components/design-system/Buttons/Button';
import HuChips from '@material-hu/components/design-system/Chip';
import HuDialog from '@material-hu/components/design-system/Dialog';
import useHuSnackbar from '@material-hu/components/design-system/Snackbar';
import HuTabs from '@material-hu/components/design-system/Tabs';
import HuTitle from '@material-hu/components/design-system/Title';

import useGeneralError from 'src/hooks/useGeneralError';
import useHuGoTheme from 'src/hooks/useHuGoTheme';
import {
  cancelDraft,
  getDraftRequests,
  getDraftRequestsMine,
} from 'src/services/posts';
import { DraftStatus, DraftStatusGeneral, UserAsValues } from 'src/types/posts';
import { insertIf } from 'src/utils/arrays';
import { formatTitle } from 'src/utils/helmetUtils';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { flatPages } from 'src/utils/pagination';

import PostDraftTable from './components/PostDraftTable';
import { useCheckDraftPermission } from './hooks/useCheckDraftPermission';
import { postDraftKeys } from './queries';
import { draftsForReviewRoutes } from './routes';

const LIMIT = 10;

const DraftsForReview: FC = () => {
  const [selectedTab, setSelectedTab] = useState<UserAsValues>(
    UserAsValues.DRAFTER,
  );

  const [draftStatus, setDraftStatus] = useState<DraftStatus>(
    DraftStatus.IN_PROGRESS,
  );
  const [draftFilter, setDraftFilter] = useState<DraftStatus>(
    DraftStatus.IN_PROGRESS,
  );
  const { t } = useLokaliseTranslation(['communication', 'drafts']);
  const navigate = useNavigate();
  const HuGoThemeProvider = useHuGoTheme();
  const showGeneralError = useGeneralError();
  const { enqueueSnackbar } = useHuSnackbar();

  const {
    canCreateDraft,
    isFinalAuthor,
    draftPermissionsIsLoading,
    draftPermissionsAuthorIsLoading,
  } = useCheckDraftPermission({
    checkBoth: true,
    onSuccess: res => {
      setSelectedTab(res ? UserAsValues.DRAFTER : UserAsValues.FINAL_AUTHOR);
    },
  });

  const {
    data: draftRequestsMineInfinite,
    isLoading: draftsMineIsLoading,
    fetchNextPage: draftRequestsMineFetchNextPage,
    hasNextPage: draftRequestsMineHasNextPage,
    isFetchingNextPage: draftRequestsMineIsFetchingNextPage,
    refetch: refetchDraftRequestsMine,
  } = useInfiniteQuery(
    postDraftKeys.requestsMine(draftFilter),
    ({ pageParam = '' }) =>
      getDraftRequestsMine({
        limit: LIMIT,
        state: draftFilter,
        cursor: pageParam,
      }),
    {
      getNextPageParam: lastPage => lastPage?.data?.cursor,
      onError: err => {
        showGeneralError(
          err,
          t(
            'communication:drafts_for_review.error_loading_draft_requests_mine',
          ),
        );
      },
      enabled: selectedTab === UserAsValues.DRAFTER,
    },
  );

  const {
    data: draftRequestsInfinite,
    isLoading: draftRequestsIsLoading,
    fetchNextPage: draftRequestsFetchNextPage,
    hasNextPage: draftRequestsHasNextPage,
    isFetchingNextPage: draftRequestsIsFetchingNextPage,
    refetch: refetchDraftRequests,
  } = useInfiniteQuery(
    postDraftKeys.requests(draftFilter),
    ({ pageParam = '' }) =>
      getDraftRequests({
        limit: LIMIT,
        state: draftFilter,
        cursor: pageParam,
      }),
    {
      getNextPageParam: lastPage => lastPage?.data?.cursor,
      onError: err => {
        showGeneralError(
          err,
          t('communication:drafts_for_review.error_loading_draft_requests'),
        );
      },
      enabled: [UserAsValues.FINAL_AUTHOR, null].includes(selectedTab),
    },
  );

  const draftRequests = flatPages(
    selectedTab === UserAsValues.DRAFTER
      ? draftRequestsMineInfinite
      : draftRequestsInfinite,
  );

  const isDrafterTab = selectedTab === UserAsValues.DRAFTER;

  const isLoadingGeneral =
    [DraftStatus.IN_PROGRESS, DraftStatus.APPROVED].includes(draftFilter) &&
    (isDrafterTab ? draftsMineIsLoading : draftRequestsIsLoading);

  const isLoadingFilter =
    [DraftStatus.PENDING, DraftStatus.OVERDUE].includes(draftFilter) &&
    (isDrafterTab ? draftsMineIsLoading : draftRequestsIsLoading);

  const fetchNextPage = isDrafterTab
    ? draftRequestsMineFetchNextPage
    : draftRequestsFetchNextPage;
  const hasNextPage = isDrafterTab
    ? draftRequestsMineHasNextPage
    : draftRequestsHasNextPage;
  const isFetchingNextPage = isDrafterTab
    ? draftRequestsMineIsFetchingNextPage
    : draftRequestsIsFetchingNextPage;

  const userAsTab = [
    ...insertIf(!!canCreateDraft, {
      label: t(`drafts_for_review.as_${UserAsValues.DRAFTER}`),
      value: UserAsValues.DRAFTER,
    }),
    ...insertIf(!!isFinalAuthor, {
      label: t(`drafts_for_review.as_${UserAsValues.FINAL_AUTHOR}`),
      value: UserAsValues.FINAL_AUTHOR,
    }),
  ];

  const handleTabChange = (value: string) => {
    setSelectedTab(value as UserAsValues);
  };

  const deleteMutation = useMutation((id: number) => cancelDraft(id), {
    onSuccess: () => {
      enqueueSnackbar({
        title: t('drafts:main.cancel_post_success_title'),
        description: t(
          'communication:drafts_for_review.delete_draft_success_description',
        ),
        variant: 'success',
      });
      refetchDraftRequestsMine();
      refetchDraftRequests();
      closeDeleteModal();
    },
    onError: () => {
      enqueueSnackbar({
        title: t('communication:drafts_for_review.delete_draft_error'),
        variant: 'error',
      });
    },
  });

  const {
    modal: cancelModal,
    showModal: showDeleteModal,
    closeModal: closeDeleteModal,
  } = useModal(({ id }: { id: number }) => (
    <HuDialog
      title={t('communication:drafts_for_review.delete_draft_request_sure')}
      textBody={t('drafts:main.cancel_post_description')}
      primaryButtonProps={{
        children: t('drafts:main.cancel_post_submit'),
        onClick: () => deleteMutation.mutate(id),
        loading: deleteMutation.isLoading,
      }}
      secondaryButtonProps={{
        children: t('general:cancel'),
        onClick: closeDeleteModal,
      }}
      onClose={closeDeleteModal}
    />
  ));

  const handleDraftStatusGeneral = (status: DraftStatus) => {
    setDraftStatus(status);
    setDraftFilter(status);
  };

  return (
    <>
      <Helmet>
        <title>{formatTitle(t('communication:draft_for_review'))}</title>
      </Helmet>
      <HuGoThemeProvider>
        {cancelModal}
        <Stack
          sx={{
            backgroundColor: theme =>
              theme.palette.new.background.layout.default,
            minHeight: '100%',
            px: 12,
            py: 5,
            gap: 4,
          }}
        >
          <Stack
            sx={{
              gap: 3,
            }}
          >
            <Stack
              sx={{
                gap: 2,
                flex: 0,
                flexWrap: 'wrap',
                flexDirection: 'row',
                alignItems: 'center',
              }}
            >
              <HuTitle
                sx={{ flex: 1 }}
                variant="L"
                title={t('communication:drafts_for_review.module_title')}
                description={t(
                  'communication:drafts_for_review.module_description',
                )}
              />
              {canCreateDraft && (
                <Button
                  variant="primary"
                  size="small"
                  startIcon={<IconPlus size={16} />}
                  onClick={() => {
                    navigate(draftsForReviewRoutes.createPostDraft());
                  }}
                >
                  {t('general:create')}
                </Button>
              )}
            </Stack>
          </Stack>
          {(draftPermissionsIsLoading || draftPermissionsAuthorIsLoading) && (
            <Stack sx={{ flex: 1, alignItems: 'center' }}>
              <CircularProgress />
            </Stack>
          )}
          {!draftPermissionsIsLoading && !draftPermissionsAuthorIsLoading && (
            <>
              <HuTabs
                defaultValue={selectedTab}
                tabs={userAsTab}
                onTabChange={handleTabChange}
              />
              <Stack sx={{ flexDirection: 'row', gap: 1 }}>
                {Object.values(DraftStatusGeneral).map(status => (
                  <HuChips
                    key={status}
                    label={t(
                      'communication:drafts_for_review.draft_status_general',
                      {
                        context: status,
                      },
                    )}
                    isSelected={draftStatus === status}
                    onClick={() => handleDraftStatusGeneral(status)}
                  />
                ))}
              </Stack>
              <PostDraftTable
                draftRequests={draftRequests}
                onDelete={showDeleteModal}
                isLoadingGeneral={isLoadingGeneral}
                isLoadingFilter={isLoadingFilter}
                draftStatus={draftStatus}
                fetchNextPage={fetchNextPage}
                hasNextPage={hasNextPage}
                isFetchingNextPage={isFetchingNextPage}
                draftFilter={draftFilter}
                setDraftFilter={setDraftFilter}
                isFinalAuthorTab={[UserAsValues.FINAL_AUTHOR, null].includes(
                  selectedTab,
                )}
              />
            </>
          )}
        </Stack>
      </HuGoThemeProvider>
    </>
  );
};

export default DraftsForReview;
