import { FormProvider, useForm } from 'react-hook-form';
import { type TFunction, Trans } from 'react-i18next';

import { zodResolver } from '@hookform/resolvers/zod';
import { sample } from 'lodash-es';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';
import { IconType } from '@material-hu/types/icons';

import FormInputClassic from '@material-hu/components/design-system/Inputs/Classic/form';
import { Drawer, useDrawerLayer } from '@material-hu/components/layers/Drawers';

import { usePublicIcons } from 'src/hooks/usePublicIcons';
import { ARTICLE_TITLE_MAX_LENGTH } from 'src/pages/dashboard/HuLibraries/constants';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { useArticleFormSchema } from '../hooks/useArticleFormSchema';
import { useCachedArticle } from '../hooks/useCachedArticle';
import { useCreateArticle } from '../hooks/useCreateArticle';
import { type ArticleFormValues } from '../schemas';
import { type CreateArticlePayload } from '../types';

import { ArticleAudienceListAlert } from './ArticleAudienceListAlert';

type CreateArticleDrawerProps = {
  articleId: number | null;
};

const CreateArticleDrawer = ({ articleId }: CreateArticleDrawerProps) => {
  const isRoot = !articleId;
  const { t } = useLokaliseTranslation('libraries');
  const { closeDrawer } = useDrawerLayer();
  const { article } = useCachedArticle(articleId);
  const createArticleMutation = useCreateArticle();
  const {
    icons,
    isLoading: isIconsLoading,
    isError: isIconsError,
  } = usePublicIcons();
  const hasIconForCreate = !isIconsLoading && !isIconsError && icons.length > 0;
  const schema = useArticleFormSchema();

  const form = useForm<ArticleFormValues>({
    defaultValues: { title: '' },
    resolver: zodResolver(schema),
  });

  const { handleSubmit, formState } = form;

  const handleCreateArticle = handleSubmit(values => {
    const iconSource = sample(icons)?.source;
    if (!iconSource) return;

    const payload: CreateArticlePayload = {
      title: values.title,
      parentId: articleId ?? null,
      icon: { type: IconType.IMAGE, value: iconSource },
    };
    createArticleMutation.mutate(payload, {
      onSuccess: () => closeDrawer(),
    });
  });

  const title = isRoot ? t('article.create') : t('subarticle.create.title');

  const label = isRoot ? t('article.title_one') : t('subarticle.title_one');

  const isLoading = createArticleMutation.isLoading || isIconsLoading;

  return (
    <FormProvider {...form}>
      <Drawer.Header
        title={title}
        onClose={closeDrawer}
      />
      <Drawer.Body>
        {articleId && article?.title && (
          <Typography
            sx={{
              pb: 2,
              wordWrap: 'break-word',
              width: '100%',
              color: ({ palette }) => palette.new.text.neutral.lighter,
            }}
          >
            <Trans
              i18nKey="subarticle.adding_to_article_alert"
              ns="libraries"
              t={t as TFunction}
              values={{ articleTitle: article.title }}
              components={{
                strong: (
                  <Typography
                    fontWeight="fontWeightSemiBold"
                    component="span"
                    sx={{
                      color: ({ palette }) => palette.new.text.neutral.lighter,
                    }}
                  />
                ),
              }}
            />
          </Typography>
        )}
        <FormInputClassic
          name="title"
          inputProps={{
            label,
            placeholder: t('general:name'),
            maxLength: ARTICLE_TITLE_MAX_LENGTH,
          }}
        />
        {article?.audiencesQuery && articleId && (
          <Stack sx={{ mt: 'auto' }}>
            <ArticleAudienceListAlert
              audiencesQuery={article.audiencesQuery}
              articleId={articleId}
              titleKey="article.collaborators.amount"
            />
          </Stack>
        )}
      </Drawer.Body>
      <Drawer.Actions
        primaryButtonProps={{
          children: t('general:create'),
          fullWidth: true,
          onClick: handleCreateArticle,
          loading: isLoading,
          disabled: isLoading || !formState.isValid || !hasIconForCreate,
        }}
        secondaryButtonProps={{
          children: t('general:cancel'),
          fullWidth: true,
          disabled: isLoading,
          onClick: () => closeDrawer(),
        }}
      />
    </FormProvider>
  );
};

export default CreateArticleDrawer;
