import { useCallback, useState } from 'react';

import type { FC } from 'react';
import type { ClickableProps } from '../Clickable';

import { useTracker } from '~/src/lib/tracker/useTracker';
import ModalShare from '.';
import Clickable from '../Clickable';
import shareNative from './lib/shareNative';

const ClickableShareModal: FC<ClickableProps> = ({
  children,
  ...clickableProps
}) => {
  const [isOpen, setIsOpen] = useState(false);
  const { trackEvent } = useTracker();

  return (
    <>
      <Clickable
        {...clickableProps}
        onClick={useCallback(() => {
          const success = shareNative({
            url: location.href,
            text: document.title,
          });

          if (success) {
            trackEvent({
              type: 'share',
              shareType: 'native',
            });

            return;
          }

          setIsOpen(true);
        }, [])}
      >
        {children}
      </Clickable>
      {isOpen && <ModalShare onClose={() => setIsOpen(false)} />}
    </>
  );
};

export default ClickableShareModal;
