import { useState } from 'react';
import dynamic from 'next/dynamic';

import type { MappedContentLink } from '~/lib/songwhipApi/mapper';
import type { MenuDialogSection } from '~/src/components/MenuDialog/types';

import Box from '~/src/components/Box';
import { Clickable } from '~/src/components/Clickable';
import ChartIcon from '~/src/components/Icon/ChartIcon';
import EditIcon from '~/src/components/Icon/EditIcon';
import MoreIcon from '~/src/components/Icon/MoreIcon';
import ShareIcon from '~/src/components/Icon/ShareIcon';
import Link from '~/src/components/Link2';
import useIsLargeScreen from '~/src/hooks/useIsLargeScreen';
import { useI18n } from '~/src/lib/i18n';
import { useAppRouter } from '~/src/lib/router2';
import { useContentLinksFilters } from '../hooks';
import { ContentLinkItem } from './ContentLinkItem';

const MenuDialogLazy = dynamic({
  ssr: false,
  loader: () => import('~/src/components/MenuDialog'),
});

const ContentLinkShareDialogDynamic = dynamic({
  ssr: false,
  loader: () =>
    import('~/src/features/contentLink/components/shareDialog').then(
      (m) => m.ContentLinkShareDialog
    ),
});

export const ContentLinkItems = ({ items }: { items: MappedContentLink[] }) => {
  const { t: tApp } = useI18n('app');
  const { t } = useI18n('catalog');

  const [menuActions, setMenuActions] = useState<MenuDialogSection[]>();
  const [filters] = useContentLinksFilters();
  const isLargeScreen = useIsLargeScreen();
  const appRouter = useAppRouter();
  const [activeShareLink, setActiveShareLink] = useState<MappedContentLink>();

  const renderActions = (item: MappedContentLink) => {
    const ICON_COLOR = '#ccc';
    const ICON_SIZE = '2.3rem';
    const ICON_OPACITY = 0.65;

    return (
      <Box flexRow alignCenter gap="1.4rem" style={{ marginLeft: '1.5rem' }}>
        {isLargeScreen ? (
          <>
            <Clickable
              isInline
              title={t('actions.viewInDashboard')}
              withHoverOpacityFrom={ICON_OPACITY}
              href={`/dashboard/content-link/${item.id}`}
            >
              <ChartIcon color={ICON_COLOR} size={ICON_SIZE} />
            </Clickable>
            <Clickable
              isInline
              title={t('contentLinks.edit')}
              withHoverOpacityFrom={ICON_OPACITY}
              href={`/content-links/${item.id}/edit`}
            >
              <EditIcon color={ICON_COLOR} size={ICON_SIZE} />
            </Clickable>
            <Clickable
              isInline
              testId="contentLinkShareButton"
              title={tApp('actions.share')}
              withHoverOpacityFrom={ICON_OPACITY}
              onClick={() => {
                setActiveShareLink(item);
              }}
            >
              <ShareIcon color={ICON_COLOR} size={ICON_SIZE} />
            </Clickable>
          </>
        ) : (
          <Clickable
            testId="contentLinkItemMenu"
            isInline
            title="menu"
            withHoverOpacityFrom={ICON_OPACITY}
            onClick={() => {
              setMenuActions([
                [
                  {
                    Icon: ChartIcon,
                    content: t('actions.viewInDashboard'),
                    onClick: () => {
                      appRouter.push(`/dashboard/content-link/${item.id}`);
                    },
                  },
                  {
                    Icon: EditIcon,
                    content: t('contentLinks.edit'),
                    onClick: () => {
                      appRouter.push(`/content-links/${item.id}/edit`);
                    },
                  },
                  {
                    Icon: ShareIcon,
                    content: tApp('actions.share'),
                    onClick: () => {
                      setActiveShareLink(item);
                    },
                  },
                ],
              ]);
            }}
          >
            <MoreIcon color={ICON_COLOR} size="3rem" direction="right" />
          </Clickable>
        )}
      </Box>
    );
  };

  const content = (
    <>
      <Box flexColumn gap="2.4rem">
        {items.map((item) => (
          <ContentLinkItem
            key={item.id}
            item={item}
            renderActions={() => renderActions(item)}
          />
        ))}
      </Box>
      {menuActions && (
        <MenuDialogLazy
          sections={menuActions}
          onClose={() => setMenuActions(undefined)}
        />
      )}
      {activeShareLink && (
        <ContentLinkShareDialogDynamic
          contentLink={activeShareLink}
          onClose={() => {
            setActiveShareLink(undefined);
          }}
        />
      )}
    </>
  );

  const empty = (
    <Box centerContent flexColumn style={{ textAlign: 'center' }}>
      {filters.search ? (
        <div>{t('contentLinks.notFound', { searchValue: filters.search })}</div>
      ) : filters.artistId ? (
        <div>{t('contentLinks.notFoundByFilter')}</div>
      ) : (
        <>
          <div style={{ marginBottom: '0.5rem' }}>
            {t('contentLinks.noItems')}
          </div>
          <Link href="/create" style={{ fontWeight: 'bold' }}>
            {tApp('actions.create')}
          </Link>
        </>
      )}
    </Box>
  );

  return items.length ? content : empty;
};
