import { memo, useState } from 'react';
import { createPortal } from 'react-dom';
import { useTranslation } from 'react-i18next';
import { Comment } from '@plebbit/plebbit-react-hooks';
import { autoUpdate, flip, FloatingFocusManager, offset, shift, useClick, useDismiss, useFloating, useId, useInteractions, useRole } from '@floating-ui/react';
import styles from './post-menu-mobile.module.css';
import { getCommentMediaInfo } from '../../../lib/utils/media-utils';
import { copyShareLinkToClipboard, isValidURL, type ShareLinkType } from '../../../lib/utils/url-utils';
import { copyToClipboard } from '../../../lib/utils/clipboard-utils';
import { getBoardPath } from '../../../lib/utils/route-utils';
import { useDirectories } from '../../../hooks/use-directories';
import useEditCommentPrivileges from '../../../hooks/use-author-privileges';
import useHide from '../../../hooks/use-hide';
import EditMenu from '../../edit-menu/edit-menu';
import { isBoardView, isPostPageView } from '../../../lib/utils/view-utils';
import { useLocation, useParams } from 'react-router-dom';
import { PostMenuProps } from '../../../lib/utils/post-menu-props';

type HideButtonProps = {
  cid?: string;
  isReply?: boolean;
  postCid?: string;
  onClose?: () => void;
};

type CopyLinkButtonProps =
  | { cid: string; subplebbitAddress: string; linkType: 'thread'; onClose: () => void }
  | { subplebbitAddress: string; linkType: Exclude<ShareLinkType, 'thread'>; onClose: () => void; cid?: undefined };

const CopyLinkButton = ({ cid, subplebbitAddress, linkType, onClose }: CopyLinkButtonProps) => {
  const { t } = useTranslation();
  const directories = useDirectories();
  const boardIdentifier = getBoardPath(subplebbitAddress, directories);
  return (
    <div
      onClick={async () => {
        try {
          if (linkType === 'thread') {
            await copyShareLinkToClipboard(boardIdentifier, linkType, cid);
          } else {
            await copyShareLinkToClipboard(boardIdentifier, linkType);
          }
        } catch (error) {
          console.error('Failed to copy share link', error);
        } finally {
          onClose();
        }
      }}
    >
      <div className={styles.postMenuItem}>{t('copy_direct_link')}</div>
    </div>
  );
};

const CopyContentIdButton = ({ cid, onClose }: { cid: string; onClose: () => void }) => {
  const { t } = useTranslation();
  return (
    <div
      onClick={async () => {
        try {
          await copyToClipboard(cid);
        } catch (error) {
          console.error('Failed to copy content id', error);
        } finally {
          onClose();
        }
      }}
    >
      <div className={styles.postMenuItem}>{t('copy_content_id')}</div>
    </div>
  );
};

const CopyUserIdButton = ({ address, onClose }: { address: string; onClose: () => void }) => {
  const { t } = useTranslation();
  return (
    <div
      onClick={async () => {
        try {
          await copyToClipboard(address);
        } catch (error) {
          console.error('Failed to copy user id', error);
        } finally {
          onClose();
        }
      }}
    >
      <div className={styles.postMenuItem}>{t('copy_user_id')}</div>
    </div>
  );
};

const ImageSearchButtons = ({ url, onClose }: { url: string; onClose: () => void }) => {
  const { t } = useTranslation();
  return (
    <div onClick={onClose}>
      <a href={`https://lens.google.com/uploadbyurl?url=${url}`} target='_blank' rel='noreferrer'>
        <div className={styles.postMenuItem}>{t('search_image_on_google')}</div>
      </a>
      <a href={`https://www.yandex.com/images/search?img_url=${url}&rpt=imageview`} target='_blank' rel='noreferrer'>
        <div className={styles.postMenuItem}>{t('search_image_on_yandex')}</div>
      </a>
      <a href={`https://saucenao.com/search.php?url=${url}`} target='_blank' rel='noreferrer'>
        <div className={styles.postMenuItem}>{t('search_image_on_saucenao')}</div>
      </a>
    </div>
  );
};

const HidePostButton = ({ cid, isReply, onClose, postCid }: HideButtonProps) => {
  const { t } = useTranslation();
  const { hide, hidden, unhide } = useHide({ cid: cid || '' });
  const isInPostView = isPostPageView(useLocation().pathname, useParams());

  return (
    (!isInPostView || isReply) && (
      <div
        onClick={() => {
          hidden ? unhide() : hide();
          onClose && onClose();
        }}
      >
        <div className={styles.postMenuItem}>
          {hidden ? (postCid === cid ? t('unhide_thread') : t('unhide_post')) : postCid === cid ? t('hide_thread') : t('hide_post')}
        </div>
      </div>
    )
  );
};

type PostMenuMobileProps = {
  postMenu: PostMenuProps;
  editMenuPost: Comment;
};

const PostMenuMobile = ({ postMenu, editMenuPost }: PostMenuMobileProps) => {
  const { authorAddress, cid, deleted, link, linkHeight, linkWidth, parentCid, postCid, removed, subplebbitAddress, thumbnailUrl } = postMenu || {};
  const { isAccountMod, isAccountCommentAuthor } = useEditCommentPrivileges({
    commentAuthorAddress: authorAddress || '',
    subplebbitAddress: subplebbitAddress || '',
  });
  const commentMediaInfo = getCommentMediaInfo(link || '', thumbnailUrl || '', linkWidth || 0, linkHeight || 0);
  const { thumbnail, type, url } = commentMediaInfo || {};
  const [isMenuOpen, setIsMenuOpen] = useState(false);
  const { refs, floatingStyles, context } = useFloating({
    placement: 'bottom-start',
    open: isMenuOpen,
    onOpenChange: setIsMenuOpen,
    middleware: [offset({ mainAxis: 3, crossAxis: 8 }), flip(), shift({ padding: 10 })],
    whileElementsMounted: autoUpdate,
  });
  const click = useClick(context);
  const dismiss = useDismiss(context);
  const role = useRole(context);
  const { getReferenceProps, getFloatingProps } = useInteractions([click, dismiss, role]);
  const headingId = useId();

  const handleMenuClick = () => {
    if (cid) {
      setIsMenuOpen((prev) => !prev);
    }
  };

  const handleClose = () => setIsMenuOpen(false);

  const isInBoardView = isBoardView(useLocation().pathname, useParams());

  return (
    <>
      {!(deleted || removed) && (
        <>
          <span className={styles.postMenuBtn} title='Post menu' onClick={handleMenuClick} ref={refs.setReference} {...getReferenceProps()}>
            ...
          </span>
          {isMenuOpen &&
            cid &&
            createPortal(
              <FloatingFocusManager context={context} modal={false}>
                <div className={styles.postMenu} ref={refs.setFloating} style={floatingStyles} aria-labelledby={headingId} {...getFloatingProps()}>
                  {cid && subplebbitAddress && <CopyLinkButton cid={cid} subplebbitAddress={subplebbitAddress} linkType='thread' onClose={handleClose} />}
                  {cid && <CopyContentIdButton cid={cid} onClose={handleClose} />}
                  {authorAddress && <CopyUserIdButton address={authorAddress} onClose={handleClose} />}
                  {cid && subplebbitAddress && <HidePostButton cid={cid} isReply={!!parentCid} postCid={postCid} onClose={handleClose} />}
                  {link && isValidURL(link) && (type === 'image' || type === 'gif' || thumbnail) && url && <ImageSearchButtons url={url} onClose={handleClose} />}
                </div>
              </FloatingFocusManager>,
              document.body,
            )}
        </>
      )}
      {(isAccountMod || isAccountCommentAuthor) && cid && (
        <span className={styles.checkbox}>
          <EditMenu post={editMenuPost} />
        </span>
      )}
    </>
  );
};

export default memo(PostMenuMobile);
