import { useCallback, useState } from 'react';

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

import ItemPageActions from '~/src/components/ItemPage/components/ItemPageActions';
import { toShareUrl } from '~/src/components/ItemPage/utils';
import LazyComponent from '~/src/components/LazyComponent';
import {
  useAppConfirm,
  useAppToast,
} from '~/src/components/NextApp/lib/CoreUi';
import useFetchSessionUser from '~/src/hooks/useFetchSessionUser';
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 deleteAlbumAction from '~/src/store/albums/actions/deleteAlbum';
import { useDispatch } from '~/src/store/redux';

export const AlbumPageActions: FC<{
  itemContext: AlbumItemContext;
  isOpen: boolean;
  actionButtonRef: RefObject<HTMLElement | null>;
  onClose: () => void;
  showMissingServicesBanner?: boolean;
  userCanEdit: boolean;
}> = ({
  itemContext,
  isOpen,
  actionButtonRef,
  onClose,
  showMissingServicesBanner,
  userCanEdit,
}) => {
  const { isAdmin } = useFetchSessionUser();
  const showConfirmDialog = useAppConfirm();
  const { showArtistIds, hasArtistActions } = itemContext.config;
  const artists = useSelectArtists(showArtistIds);
  const artistNames = artists?.map(({ name }) => name).join(', ');
  const router = useAppRouter();
  const album = itemContext.data.item;
  const dispatch = useDispatch();
  const showToast = useAppToast();
  const { t } = useI18n();
  const [addMissingLinksDialogOpen, setAddMissingLinksDialogOpen] =
    useState(false);

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

  const shareText = album.name && `"${album.name}" by ${artistNames}`;

  return (
    <>
      <ItemPageActions
        isOpen={isOpen}
        item={album}
        targetElRef={actionButtonRef}
        onClose={onClose}
        userCanEdit={userCanEdit}
        pagePath={album.pagePath}
        shareUrl={shareUrl}
        shareText={shareText}
        toActionItems={useCallback(
          ({ sections }) => {
            if (album.userCanEdit) {
              // Add missing links action when banner is shown
              if (showMissingServicesBanner) {
                sections[0].push({
                  content: t('item.actions.addMissingLinks'),
                  testId: 'addMissingLinks',
                  icon: 'addLinks',
                  onClick: () => {
                    setAddMissingLinksDialogOpen(true);
                  },
                });
              }

              sections[0].push({
                content: t('item.actions.viewInDashboard'),
                href: `/dashboard/album/${album.id}`,
                icon: 'chart',
                testId: 'viewInDashboard',
              });

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

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

                      onConfirm: async () => {
                        await dispatch(
                          deleteAlbumAction({
                            albumId: album.id,
                          })
                        );

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

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

            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;
          },
          [album, showMissingServicesBanner, t]
        )}
      />
      {addMissingLinksDialogOpen && (
        <LazyComponent
          loader={() =>
            import('./AddMissingLinksDialog').then(
              (m) => m.AddMissingLinksDialog
            )
          }
          onClose={() => setAddMissingLinksDialogOpen(false)}
          album={album}
        />
      )}
    </>
  );
};
