import { useCallback, useMemo } from 'react';
import { useI18n } from '@theorchard/suite-i18n-localization';

import Clickable from '~/src/components/Clickable';
import Text from '~/src/components/Text';
import useHash from '~/src/hooks/useHash';
import { useItemContext } from '../../../ItemPageContext';
import { resolveLink } from '../../lib';
import {
  AddLinkDialogBox,
  useSuggestedLinks,
} from '../../lib/AddLinkDialogBox';

const AddLinkButton = ({
  sectionPath,
  existingLinks,
  onSubmit,
}: {
  sectionPath: string;
  existingLinks: string[];
  onSubmit: (params: { dataPath: string }) => void;
}) => {
  const { hasHashParam, backToBeforeFirstHash, setHashParam } = useHash();
  const addLinkHashParam = `linkButtons:${sectionPath}:add`;
  const addLinkDialogOpen = hasHashParam(addLinkHashParam);
  const suggestedLinks = useSuggestedLinks();
  const { data } = useItemContext();
  const { t } = useI18n('itemEdit');

  const urlsInList = useMemo(
    () =>
      existingLinks
        .map((dataPath) => resolveLink(data, dataPath)?.link)
        .filter(Boolean),
    [existingLinks]
  ) as string[];

  // REVIEW: we're currently not filtering out social services here.
  // This is largely because people may still want to add these services
  // when they create ItemLinks lists that aren't 'Stream' or 'Buy'.
  const addLinkItems = useMemo(
    () =>
      suggestedLinks.map((item) => ({
        ...item,
        isInList: urlsInList.some((link) => item.urlPattern.test(link)),
      })),
    [suggestedLinks]
  );

  return (
    <>
      <Clickable
        onClick={useCallback(
          () => setHashParam({ [addLinkHashParam]: '' }),
          [setHashParam]
        )}
        margin="2rem 0 0 0"
        testId="addLinkButton"
        fullWidth
      >
        <Text size="1.8rem" isBold centered>
          {t('actions.addLink')}
        </Text>
      </Clickable>
      {addLinkDialogOpen && (
        <AddLinkDialogBox
          withPagePeekingSetting
          items={addLinkItems}
          hashParam={addLinkHashParam}
          onClose={backToBeforeFirstHash}
          onPick={onSubmit}
          onCreate={onSubmit}
        />
      )}
    </>
  );
};

export default AddLinkButton;
