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

import { zodResolver } from '@hookform/resolvers/zod';
import { type GetDrawerConfiguration } from '@material-hu/hooks/useDrawerV2';
import { useLazyModal } from '@material-hu/hooks/useLazyModal';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import FormInputClassic from '@material-hu/components/design-system/Inputs/Classic/form';

import { ARTICLE_TITLE_MAX_LENGTH } from 'src/pages/dashboard/HuLibraries/constants';
import { useArticleDuplicateSchema } from 'src/pages/dashboard/HuLibraries/hooks/useArticleDuplicateSchema';
import { useArticleId } from 'src/pages/dashboard/HuLibraries/hooks/useArticleId';
import { useDuplicateArticle } from 'src/pages/dashboard/HuLibraries/hooks/useDuplicateArticle';
import { huLibrariesRoutes } from 'src/pages/dashboard/HuLibraries/routes';
import { type DuplicateArticleFormValues } from 'src/pages/dashboard/HuLibraries/schemas';
import {
  type Article,
  type DuplicateArticlePayload,
} from 'src/pages/dashboard/HuLibraries/types';
import { useLokaliseTranslation } from 'src/utils/i18n';

const CancelDuplicateArticleModal = lazy(
  () => import('./CancelDuplicateArticleModal'),
);

type DuplicateArticleDrawerProps = GetDrawerConfiguration<{
  article: Article;
  disableUnsavedWarning: () => void;
  resetUnsavedWarning: () => void;
}>;

const DuplicateArticleDrawer: DuplicateArticleDrawerProps = ({
  article,
  closeDrawer,
  disableUnsavedWarning,
  resetUnsavedWarning,
}) => {
  const { t } = useLokaliseTranslation('libraries');
  const navigate = useNavigate();
  const schema = useArticleDuplicateSchema();
  const { rootId } = useArticleId();

  const duplicateMutation = useDuplicateArticle(article, {
    onMutate: disableUnsavedWarning,
    onError: resetUnsavedWarning,
  });

  const form = useForm<DuplicateArticleFormValues>({
    values: {
      title: '',
      parentId: article?.parentId || null,
    },
    defaultValues: { title: '', parentId: null },
    resolver: zodResolver(schema),
  });

  const { handleSubmit, reset, formState } = form;

  const { modal: cancelWarningModal, showModal: showCancelWarningModal } =
    useLazyModal(CancelDuplicateArticleModal);

  const handleCloseAndReset = () => {
    closeDrawer();
    reset();
  };

  const handleCloseDrawer = () => {
    if (formState.isDirty) {
      showCancelWarningModal({ onConfirm: handleCloseAndReset });
      return;
    }
    handleCloseAndReset();
  };

  const handleDuplicate = handleSubmit(values => {
    duplicateMutation.mutate(values as DuplicateArticlePayload, {
      onSuccess: ({ data: newArticle }) => {
        handleCloseAndReset();

        const navigateTo =
          values.parentId && rootId
            ? huLibrariesRoutes.article(rootId, newArticle.id)
            : huLibrariesRoutes.article(newArticle.id);

        navigate(navigateTo);
      },
    });
  });

  const isRoot = !article?.parentId;

  return {
    title: t('article.duplicate.title'),
    onClose: handleCloseDrawer,
    children: (
      <>
        {cancelWarningModal}
        <FormProvider {...form}>
          <Stack sx={{ gap: 2, height: '100%' }}>
            <Typography
              sx={{ color: ({ palette }) => palette.new.text.neutral.lighter }}
            >
              {isRoot && t('article.duplicate.description.root')}
              {!isRoot && (
                <Trans
                  i18nKey="article.duplicate.description.children"
                  ns="libraries"
                  t={t as TFunction}
                  values={{ articleName: article.parent?.title }}
                  components={{
                    strong: (
                      <Typography
                        fontWeight="fontWeightSemiBold"
                        component="span"
                        sx={{
                          color: ({ palette }) =>
                            palette.new.text.neutral.lighter,
                        }}
                      />
                    ),
                  }}
                />
              )}
            </Typography>
            <FormInputClassic
              name="title"
              inputProps={{
                label: t('general:inputs.title.label'),
                placeholder: t('general:inputs.title.placeholder'),
                maxLength: ARTICLE_TITLE_MAX_LENGTH,
              }}
            />
          </Stack>
        </FormProvider>
      </>
    ),
    primaryButtonProps: {
      children: t('general:create'),
      fullWidth: true,
      loading: duplicateMutation.isLoading,
      disabled: duplicateMutation.isLoading,
      onClick: handleDuplicate,
    },
    secondaryButtonProps: {
      children: t('general:cancel'),
      fullWidth: true,
      disabled: duplicateMutation.isLoading,
      onClick: handleCloseDrawer,
    },
  };
};

export default DuplicateArticleDrawer;
