import { useMemo } from 'react';

import Stack from '@material-hu/mui/Stack';

import useTimeInScreen from 'src/hooks/useTimeInScreen';
import { EventName } from 'src/types/amplitude';

import { useArticleEditMode } from '../hooks/useArticleEditMode';
import { useArticleId } from '../hooks/useArticleId';
import { useEditPermissionGuard } from '../hooks/useEditPermissionGuard';
import { useGetArticle } from '../hooks/useGetArticle';

import { ArticleDetail } from './components/ArticleDetail';
import { ArticleEdit } from './components/ArticleEdit';
import { ArticleError } from './components/ArticleError';
import { ArticleHeader } from './components/ArticleHeader';
import { ArticleSkeleton } from './components/ArticleSkeleton';

const Article = () => {
  const { articleId } = useArticleId();
  const {
    data: article,
    isLoading: articleLoading,
    isError: articleError,
    refetch,
  } = useGetArticle(articleId);

  const { showEdit } = useArticleEditMode(article);
  useEditPermissionGuard(article);

  const eventProperties = useMemo(
    () => ({
      widgetId: articleId,
      parentId: article?.parentId,
      name: article?.title,
    }),
    [articleId, article],
  );

  useTimeInScreen(EventName.WIDGET_LIBRARY_VIEW, eventProperties);

  if (articleError) return <ArticleError onRetry={refetch} />;
  if (articleLoading || !article) return <ArticleSkeleton />;
  if (showEdit) return <ArticleEdit article={article} />;

  return (
    <Stack sx={{ flex: 1, overflow: 'auto' }}>
      <ArticleHeader article={article} />
      <ArticleDetail article={article} />
    </Stack>
  );
};

export default Article;
