/* eslint jsx-a11y/click-events-have-key-events: warn */

/* eslint jsx-a11y/no-static-element-interactions: warn */
import { useStatsigClient } from '@statsig/react-bindings';
import { useCallback, useEffect, useState } from 'react';
import { createPortal } from 'react-dom';

import logWebUserEvent from '@/logging/logWebUserEvent';

interface CompleteProfileTooltipProps {
  btnRef: React.RefObject<HTMLElement | null>;
  handleDismissClaimUsername: () => void;
  onOpenWelcomeModal: () => void;
  isMobile?: boolean;
}

const CompleteProfileTooltip: React.FC<CompleteProfileTooltipProps> = ({
  btnRef,
  handleDismissClaimUsername,
  onOpenWelcomeModal,
  isMobile = false,
}) => {
  const statsigClient = useStatsigClient();
  const [tooltipPosition, setTooltipPosition] = useState({
    left: 0,
    top: 0,
    right: 0,
  });

  const updateTooltipPosition = useCallback(() => {
    if (!btnRef.current) return;

    if (isMobile) {
      setTooltipPosition({
        right:
          window.innerWidth -
          (btnRef.current.getBoundingClientRect().right || 0),
        top: (btnRef.current.getBoundingClientRect().bottom || 0) + 10,
        left: 0, // Not used in mobile
      });
    } else {
      setTooltipPosition({
        left: btnRef.current.getBoundingClientRect().right + 10,
        top: btnRef.current.getBoundingClientRect().top - 23.125,
        right: 0, // Not used in desktop
      });
    }
  }, [btnRef, isMobile]);

  useEffect(() => {
    updateTooltipPosition();
    window.addEventListener('resize', updateTooltipPosition);

    // Add listener for mobile banner close event
    const handleMobileBannerClose = () => {
      setTimeout(updateTooltipPosition, 0);
    };
    window.addEventListener('mobileBannerClosed', handleMobileBannerClose);

    // Log view event when tooltip is mounted
    logWebUserEvent({
      actionName: 'CompleteProfileTooltipViewed',
      context: {
        location: isMobile ? 'mobile' : 'desktop',
      },
    });

    return () => {
      window.removeEventListener('resize', updateTooltipPosition);
      window.removeEventListener('mobileBannerClosed', handleMobileBannerClose);
    };
  }, [updateTooltipPosition, isMobile]);

  const handleClick = () => {
    logWebUserEvent({
      actionName: 'CompleteProfileTooltipClicked',
      context: {
        location: isMobile ? 'mobile' : 'desktop',
      },
    });
    handleDismissClaimUsername();

    // Only open welcome modal if user is in the feature gate
    if (statsigClient.checkGate('new-user-welcome-onboarding')) {
      onOpenWelcomeModal();
    }
  };

  const handleClose = (method: 'click_outside' | 'close_button') => {
    logWebUserEvent({
      actionName: 'CompleteProfileTooltipClosed',
      context: {
        location: isMobile ? 'mobile' : 'desktop',
        method,
      },
    });
    handleDismissClaimUsername();
  };

  return createPortal(
    <div
      className='fixed h-[86px] w-[199px] cursor-pointer rounded-[8px] bg-[#252020] p-[10px]'
      style={{
        ...(isMobile
          ? {
              right: `${tooltipPosition.right}px`,
              top: `${tooltipPosition.top}px`,
            }
          : { left: tooltipPosition.left, top: tooltipPosition.top }),
        zIndex: 1000,
      }}
      onClick={handleClick}
    >
      <div
        style={{
          position: 'absolute',
          ...(isMobile
            ? {
                right: '15px',
                top: '-3px',
                transform: 'translateY(-50%)',
                borderLeft: '6px solid transparent',
                borderRight: '6px solid transparent',
                borderBottom: '6px solid #252020',
              }
            : {
                left: '-6px',
                top: '50%',
                transform: 'translateY(-50%)',
                borderTop: '6px solid transparent',
                borderBottom: '6px solid transparent',
                borderRight: '6px solid #252020',
              }),
          width: '0',
          height: '0',
        }}
      />
      <div
        className='absolute top-2 right-2 h-3 w-3 text-white/60 hover:text-white/80'
        onClick={(e) => {
          e.stopPropagation();
          handleClose('close_button');
        }}
      >
        <svg
          width='15'
          height='15'
          viewBox='0 0 24 24'
          fill='none'
          stroke='currentColor'
          strokeWidth='2'
        >
          <path d='M6 18L18 6M6 6l12 12' />
        </svg>
      </div>
      <div className='text-[15px] leading-[20px] font-semibold'>
        Finish your Profile
      </div>
      <div className='text-[12.5px] leading-[20px] font-medium font-normal'>
        Add your name and user name to complete your profile!
      </div>
    </div>,
    document.body
  );
};

export default CompleteProfileTooltip;
