import { useCallback } from 'react';

import type { FC, RefObject } from 'react';
import type { CustomPageItemContext } from '../types';

import { ItemTypes } from '~/lib/types';
import ItemPageActions from '~/src/components/ItemPage/components/ItemPageActions';
import useUnpublishLivePage from '~/src/components/ItemPage/hooks/useUnpublishLivePage';
import { toShareUrl } from '~/src/components/ItemPage/utils';
import { useAppToast } from '~/src/components/NextApp/lib/CoreUi';
import useHash from '~/src/hooks/useHash';
import useSelectArtists from '~/src/hooks/useSelectArtists';
import { toPublicEndpoint } from '~/src/lib/getPublicEndpoint';
import { useI18n } from '~/src/lib/i18n';
import { useAppRouter } from '~/src/lib/router2';
import deleteCustomPageAction from '~/src/store/customPages/actions/delete';
import { useDispatch } from '~/src/store/redux';

export const CustomPageActions: FC<{
  itemContext: CustomPageItemContext;
  isOpen: boolean;
  actionButtonRef: RefObject<HTMLElement | null>;
  onClose: () => void;
}> = ({ itemContext, isOpen, actionButtonRef, onClose }) => {
  const { hasArtistActions } = itemContext.config;
  const { item: customPage } = itemContext.data;

  const unpublishPage = useUnpublishLivePage(ItemTypes.CUSTOM_PAGE);
  const artists = useSelectArtists(customPage.artistIds);
  const { setHashParam } = useHash();
  const router = useAppRouter();
  const dispatch = useDispatch();
  const showToast = useAppToast();
  const { t } = useI18n();

  const shareUrl = toShareUrl({
    isOwned: customPage.isOwned,
    isDraft: customPage.isDraft,
    pageBrand: customPage.pageBrand,
  });

  const shareText = customPage.name;

  return (
    <ItemPageActions
      isOpen={isOpen}
      item={customPage}
      targetElRef={actionButtonRef}
      onClose={onClose}
      userCanEdit={!!customPage.userCanEdit}
      pagePath={customPage.pagePath}
      shareUrl={shareUrl}
      shareText={shareText}
      toActionItems={useCallback(
        ({ sections }) => {
          if (customPage.userCanEdit) {
            sections[0].push({
              content: t('item.actions.viewInDashboard'),
              href: `/dashboard/custom/${customPage.id}`,
              icon: 'chart',
              testId: 'viewInDashboard',
            });

            sections[0].push({
              content: t('item.actions.editCustomPageDetails'),
              testId: 'editDetails',
              icon: 'info',
              onClick: () => {
                setHashParam({ editDetails: '' });
              },
            });

            // don't allow unpublish draft page
            if (!customPage.isDraft) {
              sections[sections.length - 1].push({
                testId: 'unpublishPage',
                content: t('item.actions.unpublishPage'),
                icon: 'unpublish',
                onClick: () => {
                  unpublishPage({
                    itemId: customPage.id,
                    itemName: customPage.name,
                    pagePath: customPage.pagePath,
                  });
                },
              });
            }

            sections[sections.length - 1].push({
              content: t('item.actions.deletePage'),
              testId: 'deletePage',
              icon: 'delete',

              onClick: async () => {
                await dispatch(deleteCustomPageAction(customPage.id));

                await showToast({
                  text: t('item.events.customPageDeleted'),
                });

                router.push('/dashboard');
              },
            });
          }

          const artistsToShow = hasArtistActions
            ? artists?.filter(({ deleted }) => !deleted)
            : undefined;

          if (artistsToShow?.length) {
            sections.push(
              artistsToShow.map(({ name, pagePath }) => ({
                content: name,
                href: toPublicEndpoint(pagePath),
                icon: 'person',
              }))
            );
          }

          return sections;
        },
        [customPage]
      )}
    />
  );
};
