import { useEffect, useMemo } from 'react';
import { useFormContext, useWatch } from 'react-hook-form';

import useCoverPictureDrawer from '@material-hu/hooks/useCoverPictureDrawer';
import { type CoverPictureData } from '@material-hu/hooks/useCoverPictureDrawer/types';
import { useModal } from '@material-hu/hooks/useModal';
import {
  IconAspectRatioOff,
  IconPhoto,
  IconPhotoEdit,
} from '@material-hu/icons/tabler';

import defaultLibraryCover from 'src/assets/defaultLibraryCover.webp';
import {
  COVER_PICTURE_RECOMMENDED_HEIGHT,
  COVER_PICTURE_RECOMMENDED_WIDTH,
} from 'src/pages/dashboard/HuLibraries/constants';
import { type ArticleFormValues } from 'src/pages/dashboard/HuLibraries/schemas';
import { getCoverPictureSrc } from 'src/pages/dashboard/HuLibraries/utils';
import { urlToFile } from 'src/utils/files';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { RemoveCoverPictureModal } from '../components/RemoveCoverPictureModal';

export const useCoverPictureActions = () => {
  const { t } = useLokaliseTranslation('libraries');
  const { setValue, control } = useFormContext<ArticleFormValues>();

  const [showCoverPicture, coverPicture] = useWatch({
    control,
    name: ['showCoverPicture', 'coverPicture'],
  });

  const hasCoverPicture = !!showCoverPicture;

  const currentCoverSrc = useMemo(
    () => getCoverPictureSrc(showCoverPicture, coverPicture),
    [showCoverPicture, coverPicture],
  );

  useEffect(() => {
    return () => {
      if (currentCoverSrc && coverPicture?.file)
        URL.revokeObjectURL(currentCoverSrc);
    };
  }, [currentCoverSrc, coverPicture?.file]);

  const {
    coverPictureDrawer,
    showCoverPictureDrawer,
    closeCoverPictureDrawer,
  } = useCoverPictureDrawer({
    defaultSrc: currentCoverSrc,
  });

  const {
    modal: removeCoverPictureModal,
    showModal: showRemoveCoverPictureModal,
  } = useModal(RemoveCoverPictureModal);

  const handleUpdateCoverPicture = () => {
    showCoverPictureDrawer({
      defaultSrc: defaultLibraryCover,
      onConfirm: async (values: CoverPictureData) => {
        const cropped =
          values.coverPicture.cropped ??
          (await urlToFile(defaultLibraryCover, 'default-library-cover.webp'));

        const isFile = cropped instanceof File;

        setValue(
          'coverPicture',
          {
            url: isFile ? null : (cropped as string),
            file: isFile ? cropped : null,
          },
          { shouldDirty: true },
        );
        setValue('showCoverPicture', true, { shouldDirty: true });
        closeCoverPictureDrawer();
      },
      slotProps: {
        uploader: {
          aspectRatio: '4/1',
          recommendedWidth: COVER_PICTURE_RECOMMENDED_WIDTH,
          recommendedHeight: COVER_PICTURE_RECOMMENDED_HEIGHT,
        },
      },
    });
  };

  const handleRemoveCoverPicture = () => {
    showRemoveCoverPictureModal({
      onConfirm: () => {
        setValue('coverPicture', null, { shouldDirty: true });
        setValue('showCoverPicture', false, { shouldDirty: true });
      },
    });
  };

  const actions = [
    {
      when: hasCoverPicture,
      action: {
        key: 'remove-cover-picture',
        title: t('general:cover_picture.delete.title'),
        onClick: handleRemoveCoverPicture,
        avatar: { Icon: IconAspectRatioOff },
      },
    },
    {
      when: hasCoverPicture,
      action: {
        key: 'edit-cover-picture',
        title: t('general:cover_picture.edit'),
        onClick: handleUpdateCoverPicture,
        avatar: { Icon: IconPhotoEdit },
      },
    },
    {
      when: !hasCoverPicture,
      action: {
        key: 'add-cover-picture',
        title: t('general:cover_picture.add.title'),
        onClick: handleUpdateCoverPicture,
        avatar: { Icon: IconPhoto },
      },
    },
  ];

  return {
    actions,
    components: (
      <>
        {removeCoverPictureModal}
        {coverPictureDrawer}
      </>
    ),
  };
};
