import { FormProvider, useForm } from 'react-hook-form';

import { zodResolver } from '@hookform/resolvers/zod';
import Stack from '@material-hu/mui/Stack';

import useUnsavedWarning from 'src/hooks/useUnsavedWarning';
import { useArticleFormSchema } from 'src/pages/dashboard/HuLibraries/hooks/useArticleFormSchema';
import { useNavigateToCurrentArticle } from 'src/pages/dashboard/HuLibraries/hooks/useNavigateToCurrentArticle';
import { useUpdateArticle } from 'src/pages/dashboard/HuLibraries/hooks/useUpdateArticle';
import { type ArticleFormValues } from 'src/pages/dashboard/HuLibraries/schemas';
import { type Article } from 'src/pages/dashboard/HuLibraries/types';
import { formatArticleEditDefaults } from 'src/pages/dashboard/HuLibraries/utils';

import { ArticleEditContent } from './components/ArticleEditContent';
import { ArticleEditHeader } from './components/ArticleEditHeader';
import { CloseEditModal } from './components/CloseEditModal';

type ArticleEditProps = {
  article: Article;
};

export const ArticleEdit = ({ article }: ArticleEditProps) => {
  const schema = useArticleFormSchema();
  const navigateToArticle = useNavigateToCurrentArticle();

  const { handleSubmit, formState, ...form } = useForm<ArticleFormValues>({
    defaultValues: formatArticleEditDefaults(article),
    resolver: zodResolver(schema),
  });

  const {
    modal: unsavedModal,
    disableUnsavedWarning,
    resetUnsavedWarning,
  } = useUnsavedWarning(CloseEditModal, !formState.isDirty);

  const updateMutation = useUpdateArticle(article, {
    onMutate: () => disableUnsavedWarning(),
    onSuccess: () => navigateToArticle(),
    onSettled: () => resetUnsavedWarning(),
  });

  const handleSave = handleSubmit(values => {
    if (!formState.isDirty) {
      navigateToArticle();
      return;
    }
    updateMutation.mutate({ values, dirtyFields: formState.dirtyFields });
  });

  const isSaving = updateMutation.isLoading || updateMutation.isSuccess;

  return (
    <FormProvider
      handleSubmit={handleSubmit}
      formState={formState}
      {...form}
    >
      {unsavedModal}
      <Stack sx={{ flex: 1, overflow: 'auto' }}>
        <ArticleEditHeader
          article={article}
          onSave={handleSave}
          isSaving={isSaving}
          disableUnsavedWarning={disableUnsavedWarning}
          resetUnsavedWarning={resetUnsavedWarning}
        />
        <ArticleEditContent article={article} />
      </Stack>
    </FormProvider>
  );
};
