import { useTranslation } from 'react-i18next';
import { useQuery } from 'react-query';
import { useNavigate, useParams } from 'react-router-dom';

import CardContent from '@material-hu/mui/CardContent';
import CardHeader from '@material-hu/mui/CardHeader';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import useHuSnackbar from '@material-hu/components/design-system/Snackbar';

import useTimeInScreen from 'src/hooks/useTimeInScreen';
import * as newsService from 'src/services/newsService';
import { LogEvents, logEvent } from 'src/utils/logging';

import ArticleEditLayout from 'src/components/ArticleEditLayout';
import CircularProgress from 'src/components/CircularProgress';
import FormCheckbox from 'src/components/FormInputs/FormCheckbox';

import { newsKeys } from '../queries';
import { newsRoutes } from '../routes';

const Edit = () => {
  const { id } = useParams();
  const { t } = useTranslation(['news', 'general']);
  const getTimeInScreen = useTimeInScreen();
  const navigate = useNavigate();
  const { enqueueSnackbar } = useHuSnackbar();

  const { isLoading, isFetching, data } = useQuery(
    newsKeys.article(id!),
    () => newsService.getNew(id!),
    {
      onError: () => {
        navigate('/');
        enqueueSnackbar({ title: t('general:not_found'), variant: 'error' });
      },
      enabled: !!id,
    },
  );

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

  const mutationFn = (articleData: newsService.ArticleData) => {
    if (id) return newsService.updateNews(parseInt(id), articleData);
    return newsService.createNews(articleData);
  };

  const article = data?.data;

  return (
    <ArticleEditLayout
      recommendedCoverHeight={350}
      title={t(`news:${article ? 'edit' : 'new'}_article`)}
      successMessage={t('news:success')}
      article={article}
      backLink={newsRoutes.base()}
      mutationFn={mutationFn}
      segmentationErrorMessage={t('news:must_select_segmentation')}
      onSuccess={(response: any) => {
        const screenTime = getTimeInScreen();
        logEvent(
          article ? LogEvents.ARTICLE_UPDATE : LogEvents.ARTICLE_CREATE,
          {
            newsId: response.data.id,
            screenTime,
            name: !article && response.data.title,
          },
        );
      }}
      mandatoryCoverPicture
      hasIcon={false}
      extraDefaultValues={{
        notifyEmail: true,
        notifyPush: true,
      }}
      isNews
      ExtraStuff={() =>
        article ? null : (
          <>
            <CardHeader title={t('news:notify_audience')} />
            <CardContent>
              <Stack sx={{ mb: 3, mt: 1 }}>
                <FormCheckbox
                  name="notifyEmail"
                  label={
                    <>
                      <Typography variant="subtitle2">
                        {t('news:email')}
                      </Typography>
                      <Typography
                        variant="body2"
                        color="secondary"
                      >
                        {t('news:email_sub')}
                      </Typography>
                    </>
                  }
                />
              </Stack>
              <FormCheckbox
                name="notifyPush"
                label={
                  <>
                    <Typography variant="subtitle2">
                      {t('news:push')}
                    </Typography>
                    <Typography
                      variant="body2"
                      color="secondary"
                    >
                      {t('news:push_sub')}
                    </Typography>
                  </>
                }
              />
            </CardContent>
          </>
        )
      }
    />
  );
};

export default Edit;
