import { useCallback } from 'react';

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

import ItemPageActions from '~/src/components/ItemPage/components/ItemPageActions';
import { toShareUrl } from '~/src/components/ItemPage/utils';
import {
  useAppConfirm,
  useAppToast,
} from '~/src/components/NextApp/lib/CoreUi';
import { useI18n } from '~/src/lib/i18n';
import { useAppRouter } from '~/src/lib/router2';
import hideArtistAction from '~/src/store/artists/actions/hideArtist';
import { useDispatch } from '~/src/store/redux';

export const ArtistPageActions: FC<{
  itemContext: ArtistItemContext;
  isOpen: boolean;
  actionButtonRef: RefObject<HTMLElement | null>;
  onClose: () => void;
}> = ({ itemContext, isOpen, actionButtonRef, onClose }) => {
  const showConfirmDialog = useAppConfirm();
  const dispatch = useDispatch();
  const router = useAppRouter();
  const showToast = useAppToast();
  const artist = itemContext.data.item;
  const { t } = useI18n();

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

  const shareText = artist.name;

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

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

              onClick: () => {
                showConfirmDialog({
                  content: t('item.confirmPageDelete'),
                  actionText: t('app.actions.delete'),
                  cancelText: t('app.actions.cancel'),

                  onConfirm: async () => {
                    await dispatch(
                      hideArtistAction({
                        artistId: artist.id,
                      })
                    );

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

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

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