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

import { type GetDrawerConfiguration } from '@material-hu/hooks/useDrawerV2';
import Stack from '@material-hu/mui/Stack';

import defaultLibraryCover from 'src/assets/defaultLibraryCover.webp';
import { handleAction } from 'src/utils/events';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { LogEvents, logEvent } from 'src/utils/logging';

import { useUpdateLibraryHomeConfig } from '../../hooks/useUpdateLibraryHomeConfig';
import { type LibraryHomeConfig } from '../../types';

import { HomeCoverPicture } from './HomeCoverPicture';
import { HomeDescription } from './HomeDescription';
import {
  createLibraryHomeCoverFormValues,
  type LibraryHomeEditFormValues,
} from './libraryHomeEditForm';

export type EditLibraryHomeDrawerPayload = {
  baselineDescription: string;
  description: string;
  coverFile?: File;
  originalCoverFile?: File;
  originalCoverSrc?: string;
  shouldRemoveCover: boolean;
};

type EditLibraryHomeDrawerProps = GetDrawerConfiguration<LibraryHomeConfig>;

const EditLibraryHomeDrawer: EditLibraryHomeDrawerProps = ({
  closeDrawer,
  ...config
}) => {
  const { t } = useLokaliseTranslation();
  const updateConfigMutation = useUpdateLibraryHomeConfig();

  const form = useForm<LibraryHomeEditFormValues>({
    values: {
      description: config?.description ?? '',
      cover: createLibraryHomeCoverFormValues(
        config?.imageUrl || defaultLibraryCover,
        defaultLibraryCover,
        config?.originalImageUrl,
      ),
    },
  });

  const { reset, getValues } = form;

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

  const handleSave = () => {
    if (updateConfigMutation.isLoading) return;
    const { cover, description: nextDescription } = getValues();

    const coverFile =
      cover?.cropped instanceof File ? cover.cropped : undefined;
    const shouldRemoveCover =
      config?.imageUrl != null && !coverFile && !cover?.cropped;
    const coverSrcPayload =
      typeof cover?.cropped === 'string' ? cover.cropped : '';
    const originalCoverFile =
      cover?.original instanceof File ? cover.original : undefined;
    const originalCoverSrc =
      typeof cover?.original === 'string' ? cover.original : undefined;

    const hasCustomCover =
      Boolean(coverFile) || (coverSrcPayload !== '' && !shouldRemoveCover);

    updateConfigMutation.mutate(
      {
        baselineDescription: config?.description ?? '',
        coverFile,
        originalCoverFile,
        originalCoverSrc,
        description: nextDescription,
        shouldRemoveCover,
      },
      {
        onSuccess: () => {
          closeDrawer();
          logEvent(LogEvents.LIBRARIES_HOME_SAVED, {
            hasCustomCover,
            hasDescription: nextDescription.trim() !== '',
          });
        },
      },
    );
  };

  return {
    title: t('general:edit'),
    onClose: handleClose,
    children: (
      <FormProvider {...form}>
        <Stack sx={{ gap: 2 }}>
          <HomeCoverPicture
            defaultCoverSrc={defaultLibraryCover}
            disabled={updateConfigMutation.isLoading}
          />
          <HomeDescription disabled={updateConfigMutation.isLoading} />
        </Stack>
      </FormProvider>
    ),
    primaryButtonProps: {
      children: t('general:save'),
      fullWidth: true,
      disabled: updateConfigMutation.isLoading,
      loading: updateConfigMutation.isLoading,
      onClick: handleAction(handleSave),
    },
    secondaryButtonProps: {
      children: t('general:cancel'),
      fullWidth: true,
      disabled: updateConfigMutation.isLoading,
      onClick: handleAction(handleClose),
    },
  };
};

export default EditLibraryHomeDrawer;
