'use client';

import { useEffect, useState } from 'react';
import { useIsClient } from 'usehooks-ts';

import Link from '@/components/link/Link';
import { useAnalyticsContext } from '@/context/AnalyticsContext';
import { useMobileBanner } from '@/context/MobileBannerContext';
import logWebUserEvent from '@/logging/logWebUserEvent';
import { APPLE_APP_STORE_URL } from '@/utils/constants';
import { isAndroid, isIOS } from '@/utils/device';
import { hasTimedStorageKeyExpired, setTimedStorageKey } from '@/utils/storage';

const BANNER_DISMISSED_KEY = 'mobile-banner-dismissed';
const BANNER_DISMISSED_TTL = 7 * 24 * 60 * 60 * 1000; // 7 days

const MobileBanner: React.FC<{
  supportedBrowser: boolean | undefined;
  supportedCountries?: string[];
  title?: string;
  description?: string;
  link?: string;
  actionText?: string;
}> = ({
  supportedBrowser,
  supportedCountries,
  title = 'Suno - AI Songs',
  description = 'AI music and song generator',
  link = APPLE_APP_STORE_URL,
  actionText = 'view',
}) => {
  const [showBanner, setShowBanner] = useState(false);
  const { isBannerVisible, setIsBannerVisible } = useMobileBanner();
  const { country } = useAnalyticsContext();

  // If supportedCountries is undefined, assume all are supported
  const isSupportedCountry =
    !supportedCountries ||
    (country &&
      supportedCountries.find(
        (c) => c.toLowerCase() === country.toLowerCase()
      ) !== undefined);

  const isClient = useIsClient();
  const isOnIOS = isClient && isIOS();
  const isOnAndroid = isClient && isAndroid();

  const displayBanner =
    (supportedBrowser || isOnIOS || isOnAndroid) && isSupportedCountry;

  // Show the banner if it's not been dismissed recently
  useEffect(() => {
    if (hasTimedStorageKeyExpired(BANNER_DISMISSED_KEY)) {
      setShowBanner(true);
      if (displayBanner) {
        setIsBannerVisible(true);
      }
      window.dispatchEvent(new Event('mobileBannerShown'));
    }
  }, [setIsBannerVisible, isOnIOS, isOnAndroid, isSupportedCountry]);

  useEffect(() => {
    if (isBannerVisible && (!showBanner || !displayBanner)) {
      setIsBannerVisible(false);
    }
  }, [showBanner, displayBanner, isBannerVisible]);

  if (isOnIOS) {
    link = 'https://suno.com/ios';
  } else if (isOnAndroid) {
    link = 'https://suno.com/android';
  }

  return (
    showBanner &&
    displayBanner && (
      <div
        aria-label='Mobile App Banner'
        className='z-50 flex h-18 w-full items-center gap-2 bg-[#1c242c] px-3 md:hidden'
      >
        <button
          aria-label='Close Mobile App Banner'
          onClick={() => {
            setShowBanner(false);
            setIsBannerVisible(false);
            setTimedStorageKey(BANNER_DISMISSED_KEY, BANNER_DISMISSED_TTL);
            // Dispatch custom event for claim username tooltip repositioning
            window.dispatchEvent(new Event('mobileBannerClosed'));
            logWebUserEvent({
              actionName: 'MobileBannerClosed',
              context: {
                isIOS: isOnIOS,
                isAndroid: isOnAndroid,
              },
            });
          }}
        >
          <svg
            xmlns='http://www.w3.org/2000/svg'
            className='h-4 w-4 text-dumbo-600'
            viewBox='0 0 384 512'
          >
            <path d='M192 233.4L59.5 100.9l-22.6 22.6L169.4 256 36.9 388.5l22.6 22.6L192 278.6l132.5 132.5 22.6-22.6L214.6 256l132.5-132.5-22.6-22.6L192 233.4z'></path>
          </svg>
        </button>

        <Link
          className='flex w-full items-center gap-2'
          href={link}
          target='_blank'
          rel='noopener noreferrer'
          onClick={() => {
            logWebUserEvent({
              actionName: 'MobileBannerClicked',
              context: {
                isIOS: isOnIOS,
                isAndroid: isOnAndroid,
              },
            });
          }}
        >
          <img
            className='relative flex aspect-square h-14 w-14 shrink-0 overflow-hidden rounded-xl'
            src='https://cdn-o.suno.com/apple-touch-icon.png'
            alt='mobile banner'
          />

          <section className='flex w-full items-center justify-between font-sans'>
            <div className='flex flex-col justify-center'>
              <h1>{title}</h1>
              <p className='text-xs text-dumbo-600'>{description}</p>
            </div>
            <button className='rounded-full bg-white px-4 py-1 text-sm font-semibold text-[#1c242c] uppercase hover:brightness-60'>
              {actionText}
            </button>
          </section>
        </Link>
      </div>
    )
  );
};

export default MobileBanner;
