'use client';

import { useAuth, useClerk } from '@clerk/nextjs';
import { AnimatePresence, motion } from 'framer-motion';
import Image from 'next/image';
import { usePathname, useSearchParams } from 'next/navigation';
import React, { useEffect, useState } from 'react';

import { useApiClient } from '@/lib/apiClient';
import logWebUserEvent from '@/logging/logWebUserEvent';
import { REDIRECT_DISMISSED_KEY } from '@/utils/constants';
import { isIOS } from '@/utils/device';
import { getShareCodeDetails } from '@/utils/share';
import { hasTimedStorageKeyExpired } from '@/utils/storage';
import { getClerkSignUpRedirectProps } from '@/utils/utils';

const JOIN_FRIEND_MODAL_DELAY = 15000;

const JoinFriendModal = ({
  clipId,
  onModalShown,
  disabled,
  hideOnMobileWebRedirect = true,
}: {
  clipId: string;
  onModalShown?: (shown: boolean) => void;
  disabled?: boolean;
  hideOnMobileWebRedirect?: boolean;
}) => {
  const [show, setShow] = useState(false);
  const [shownMobileRedirect, setShownMobileRedirect] = useState(false);
  const pathname = usePathname();
  const searchParams = useSearchParams();

  const { isSignedIn } = useAuth();
  const clerk = useClerk();
  const apiClient = useApiClient();

  const shareCode = searchParams.get('sh');

  const [friendName, setFriendName] = useState('');
  const [avatarUrl, setAvatarUrl] = useState('');

  useEffect(() => {
    // Show the redirect if it's not been dismissed recently
    if (hasTimedStorageKeyExpired(REDIRECT_DISMISSED_KEY) && isIOS()) {
      setShownMobileRedirect(true);
    }
  }, []);

  useEffect(() => {
    // Don't show modal if user is already signed in
    if (isSignedIn) {
      onModalShown?.(false);
      return;
    }

    // Show modal after 30 seconds
    const timer = setTimeout(async () => {
      if (
        !shareCode ||
        disabled ||
        (hideOnMobileWebRedirect && shownMobileRedirect)
      ) {
        onModalShown?.(false);
        return;
      }

      try {
        const shareCodeDetails = await getShareCodeDetails(
          apiClient,
          shareCode
        );
        if (
          !shareCodeDetails ||
          !shareCodeDetails.success ||
          !shareCodeDetails.sharer_display_name
        ) {
          onModalShown?.(false);
          return;
        }

        setFriendName(shareCodeDetails.sharer_display_name || '');
        setAvatarUrl(shareCodeDetails.sharer_avatar_url || '');
        setShow(true);
        onModalShown?.(true);
        logWebUserEvent({
          actionName: 'JoinFriendModalOpened',
          context: {
            clipId,
            shareId: shareCode,
          },
        });
      } catch (error) {
        // console.error('Error fetching share code details:', error);
        onModalShown?.(false);
      }
    }, JOIN_FRIEND_MODAL_DELAY);

    return () => clearTimeout(timer);
  }, [isSignedIn, shareCode, apiClient, disabled]);

  const handleDismiss = () => {
    // Log the event when user dismisses the join friend modal
    if (shareCode) {
      logWebUserEvent({
        actionName: 'JoinFriendModalDismissed',
        context: {
          clipId,
          shareId: shareCode,
        },
      });
    }
    onModalShown?.(!!shareCode);
    setShow(false);
  };

  const handleSignUp = () => {
    clerk.openSignUp({
      ...getClerkSignUpRedirectProps(`${pathname}?${searchParams.toString()}`),
    });
    if (shareCode) {
      logWebUserEvent({
        actionName: 'JoinFriendModalSignUpClicked',
        context: {
          clipId,
          shareId: shareCode,
        },
      });
    }
  };

  return (
    <AnimatePresence>
      {show && (
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          transition={{ duration: 0.2 }}
          className='fixed inset-0 z-50 flex items-center justify-center bg-black/50'
          onClick={handleDismiss}
        >
          <motion.div
            initial={{ scale: 0.9, opacity: 0 }}
            animate={{ scale: 1, opacity: 1 }}
            exit={{ scale: 0.9, opacity: 0 }}
            transition={{ duration: 0.3 }}
            className='w-[90%] max-w-[320px] rounded-2xl bg-white p-6 text-center shadow-lg'
            onClick={(e) => e.stopPropagation()}
          >
            <div className='flex flex-col items-center space-y-4'>
              <div className='relative h-20 w-20 overflow-hidden rounded-full border-2 border-white'>
                {avatarUrl ? (
                  <Image
                    src={avatarUrl}
                    alt={friendName}
                    fill
                    className='object-cover'
                  />
                ) : (
                  <div className='flex h-full w-full items-center justify-center bg-linear-to-r from-amethyst-300 to-strawberry-500 text-2xl font-bold text-white'>
                    {friendName.charAt(0).toUpperCase()}
                  </div>
                )}
              </div>

              <h2 className='text-xl text-dumbo-50'>
                Join {friendName} on Suno
              </h2>

              <p className='text-sm text-dumbo-50'>
                Like what you hear? Make your own music.
              </p>

              <button
                className="w-full rounded-full bg-[url('https://cdn1.suno.ai/mwr-button-aura.jpg')] bg-cover bg-center px-4 py-3 font-medium text-white transition-opacity hover:opacity-90"
                onClick={handleSignUp}
              >
                Sign up for free
              </button>
            </div>
          </motion.div>
        </motion.div>
      )}
    </AnimatePresence>
  );
};

export default JoinFriendModal;
