'use client';

import {
  Menu,
  Modal,
  ModalBody,
  ModalContent,
  ModalOverlay,
} from '@chakra-ui/react';
import { useAuth, useClerk } from '@clerk/nextjs';
import { useGateValue, useStatsigClient } from '@statsig/react-bindings';
import clsx from 'clsx';
import { observer } from 'mobx-react-lite';
import { usePathname, useRouter } from 'next/navigation';
import React, {
  ReactNode,
  useCallback,
  useEffect,
  useRef,
  useState,
} from 'react';
import { useTranslation } from 'react-i18next';
import { twMerge } from 'tailwind-merge';

import { useStores } from '@/app/(root)/AppProviders';
import { isLiveRadioPath } from '@/app/(root)/live-radio/util';
import Button, {
  ButtonShape,
  ButtonSize,
  ButtonVariant,
} from '@/components/button/Button';
import CloseButton from '@/components/button/CloseButton';
import Logo from '@/components/image/Logo';
import Link from '@/components/link/Link';
import { MobileRootMenuItem } from '@/components/menu/MobileRootMenu';
import WelcomeModal from '@/components/modal/WelcomeModal';
import NotificationDot from '@/components/notification/NotificationDot';
import NotificationList from '@/components/notification/listView/NotificationList';
import { MediaQueryOnly } from '@/components/responsive/Responsive';
import SocialMediaBar from '@/components/section/SocialMediaBar';
import CompleteProfileTooltip from '@/components/tooltip/CompleteProfileTooltip';
import useDisclosure from '@/hooks/useDisclosure';
import {
  ArrowRightIcon,
  CloseIcon,
  ExploreIcon,
  HomeIcon,
  HooksIcon,
  LibraryIcon,
} from '@/icons';
import {
  CreateIcon,
  MoreHorizontalIcon,
  NotificationsIcon,
  SearchIcon,
} from '@/icons';
import logWebUserEvent from '@/logging/logWebUserEvent';
import {
  REFERRER_PARAM,
  SIGNUP_SOURCE_PARAM,
  SIGNUP_SOURCE_VALUES,
  TAILWIND_MEDIUM_MIN_WIDTH,
} from '@/utils/constants';
import { MOBILE_BOTTOM_NAV_FONT_SIZE } from '@/utils/constants';
import {
  colorVar,
  getClerkSignInRedirectProps,
  getSignUpSource,
} from '@/utils/utils';

import ProfileMenu from './ProfileMenu';

let searchTimeout: ReturnType<typeof setTimeout> | null;

const MobileMoreMenuModal: React.FC<{
  isOpen: boolean;
  onOpen?: () => void;
  onClose: () => void;
  onOpenFeedback: () => void;
}> = (props) => {
  const { t } = useTranslation();
  const { session } = useStores();
  const statsigClient = useStatsigClient();
  const hooksEnabled = statsigClient.checkGate('web-hooks-2025');
  const {
    isOpen: isMobileRootMenuOpen,
    // onOpen: onOpenMobileRootMenu,
    onClose: onCloseMobileRootMenu,
    onOpenFeedback,
  } = props;

  return (
    <Modal
      isOpen={isMobileRootMenuOpen}
      onClose={onCloseMobileRootMenu}
      size='full'
      isCentered
    >
      <ModalOverlay sx={{ bgColor: colorVar('background/primary') }} />
      <ModalContent
        sx={{ bgColor: colorVar('background/primary') }}
        marginY='auto'
      >
        <div className='absolute top-2 right-2'>
          <CloseButton onClick={onCloseMobileRootMenu} />
        </div>
        <ModalBody sx={{ bgColor: colorVar('background/primary') }} mt={20}>
          <div className='flex flex-1 flex-col'>
            {hooksEnabled && (
              <MobileRootMenuItem
                href='/hooks'
                onClose={onCloseMobileRootMenu}
                fontSize={MOBILE_BOTTOM_NAV_FONT_SIZE}
                color='var(--color-foreground-primary)'
              >
                {t('nav.hooks')}
              </MobileRootMenuItem>
            )}
            <MobileRootMenuItem
              href='/live-radio'
              onClose={onCloseMobileRootMenu}
              fontSize={MOBILE_BOTTOM_NAV_FONT_SIZE}
              color='var(--color-foreground-primary)'
            >
              Radio
            </MobileRootMenuItem>
            <MobileRootMenuItem
              href='https://help.suno.com'
              onClose={onCloseMobileRootMenu}
              fontSize={MOBILE_BOTTOM_NAV_FONT_SIZE}
              color='var(--color-foreground-primary)'
            >
              {t('nav.help')}
            </MobileRootMenuItem>

            <MobileRootMenuItem
              href='https://suno.com/about'
              onClose={onCloseMobileRootMenu}
              fontSize={MOBILE_BOTTOM_NAV_FONT_SIZE}
              color='var(--color-foreground-primary)'
            >
              {t('nav.about')}
            </MobileRootMenuItem>
            <MobileRootMenuItem
              href='https://suno.com/blog'
              onClose={onCloseMobileRootMenu}
              fontSize={MOBILE_BOTTOM_NAV_FONT_SIZE}
              color='var(--color-foreground-primary)'
            >
              {t('nav.blog')}
            </MobileRootMenuItem>
            {session.user && (
              <MobileRootMenuItem
                onClose={() => {
                  onCloseMobileRootMenu();
                  onOpenFeedback();
                }}
                fontSize={MOBILE_BOTTOM_NAV_FONT_SIZE}
                color='var(--color-foreground-primary)'
              >
                {t('nav.feedback')}
              </MobileRootMenuItem>
            )}
            <MobileRootMenuItem
              href='https://jobs.ashbyhq.com/suno'
              onClose={onCloseMobileRootMenu}
              fontSize={MOBILE_BOTTOM_NAV_FONT_SIZE}
              color='var(--color-foreground-primary)'
            >
              {t('nav.careers')}
            </MobileRootMenuItem>
            <MobileRootMenuItem
              href='https://suno.com/terms'
              onClose={onCloseMobileRootMenu}
              fontSize={MOBILE_BOTTOM_NAV_FONT_SIZE}
              color='var(--color-foreground-primary)'
            >
              {t('nav.terms')}
            </MobileRootMenuItem>
            <MobileRootMenuItem
              href='https://suno.com/privacy'
              onClose={onCloseMobileRootMenu}
              fontSize={MOBILE_BOTTOM_NAV_FONT_SIZE}
              color='var(--color-foreground-primary)'
            >
              {t('nav.privacy')}
            </MobileRootMenuItem>
          </div>
          <SocialMediaBar />
        </ModalBody>
      </ModalContent>
    </Modal>
  );
};

const MobileNavTab = (props: {
  href: string;
  contextName: string;
  children: ReactNode;
  onClick?: (e: any) => void;
  className?: string;
}) => {
  const { href, children, onClick, className } = props;
  const pathname = usePathname();
  return (
    <Link
      className={twMerge(
        clsx(
          'rounded-full py-1.5 text-center font-sans',
          'px-3 text-xs',
          '@xs:px-3 @xs:text-sm',
          '@sm:px-3 @sm:text-base',
          {
            'bg-foreground-primary text-background-primary': pathname === href,
            'bg-background-primary text-foreground-primary': pathname !== href,
          },
          className
        )
      )}
      href={href}
      onClick={onClick}
    >
      {children}
    </Link>
  );
};

interface NavProps {
  onOpenCreate?: () => void;
  onOpenFeedback: () => void;
  hideMobileTopBar?: boolean;
  enableMobileSongPageV2?: boolean;
}

export const MobileNavNew = ({
  onOpenCreate,
  onOpenFeedback,
  hideMobileTopBar = false,
  enableMobileSongPageV2 = false,
}: NavProps) => {
  const ICON_STYLE = 'w-6 h-6';

  const isHooksEnabled = useGateValue('web-hooks-2025');

  const pathname = usePathname();
  const { isSignedIn } = useAuth();
  const clerk = useClerk();
  const isSongPage = pathname.startsWith('/song/');
  const { session } = useStores();

  const { t } = useTranslation();

  const {
    isOpen: isMobileRootMenuOpen,
    onOpen: openMobileRootMenu,
    onClose: closeMobileRootMenu,
  } = useDisclosure();

  if (hideMobileTopBar) {
    return null;
  }

  let clerkRedirectOptions: Record<string, string> = {
    [REFERRER_PARAM]: pathname,
    [SIGNUP_SOURCE_PARAM]: getSignUpSource(pathname),
  };

  // TODO: Remove this once the experiment is over
  if (enableMobileSongPageV2 && isSongPage) {
    clerkRedirectOptions = {
      ...clerkRedirectOptions,
      [SIGNUP_SOURCE_PARAM]: SIGNUP_SOURCE_VALUES.MOBILE_SONG_PAGE,
    };
  }

  return (
    <div
      className={
        'flex h-[60px] w-full flex-row overflow-x-auto overflow-y-hidden bg-background-primary px-2 py-4 font-sans text-sm'
      }
    >
      <div className='@container flex w-full flex-1 flex-row items-center justify-between gap-0 bg-transparent font-medium text-foreground-primary'>
        {isHooksEnabled ? (
          <>
            <MobileNavTab href='/hooks' contextName='hooks'>
              <HooksIcon className={ICON_STYLE} />
            </MobileNavTab>
            <MobileNavTab href='/' contextName='home'>
              <ExploreIcon className={ICON_STYLE} />
            </MobileNavTab>
          </>
        ) : (
          <>
            <MobileNavTab href='/' contextName='home'>
              <HomeIcon className={ICON_STYLE} />
            </MobileNavTab>
            <MobileNavTab
              contextName='library'
              href={session.flags?.['library-v2-page'] ? '/me/v2' : '/me'}
              onClick={(e) => {
                if (!isSignedIn) {
                  const redirectUrl = session.flags?.['library-v2-page']
                    ? '/me/v2'
                    : '/me';
                  clerk.openSignIn({
                    withSignUp: true,
                    ...getClerkSignInRedirectProps(
                      redirectUrl,
                      clerkRedirectOptions
                    ),
                  });
                  e.preventDefault();
                }
              }}
            >
              <LibraryIcon className={ICON_STYLE} />
            </MobileNavTab>
          </>
        )}

        <MobileNavTab
          contextName='create'
          onClick={(e) => {
            if (!isSignedIn) {
              clerk.openSignIn({
                withSignUp: true,
                ...getClerkSignInRedirectProps('/create', clerkRedirectOptions),
              });
              e.preventDefault();
            }
            onOpenCreate?.();
          }}
          href='/create'
          className='bg-(image:--button-background-image) bg-center text-white'
        >
          <CreateIcon className={ICON_STYLE} />
        </MobileNavTab>

        {isHooksEnabled ? (
          <MobileNavTab
            contextName='library'
            href={session.flags?.['library-v2-page'] ? '/me/v2' : '/me'}
            onClick={(e) => {
              if (!isSignedIn) {
                const redirectUrl = session.flags?.['library-v2-page']
                  ? '/me/v2'
                  : '/me';
                clerk.openSignIn({
                  withSignUp: true,
                  ...getClerkSignInRedirectProps(
                    redirectUrl,
                    clerkRedirectOptions
                  ),
                });
                e.preventDefault();
              }
            }}
          >
            <LibraryIcon className={ICON_STYLE} />
          </MobileNavTab>
        ) : (
          <MobileNavTab
            contextName='explore'
            href={'https://suno.com/explore'}
            onClick={() => {
              // TODO: add new tracking on needs
            }}
          >
            <ExploreIcon className={ICON_STYLE} />
          </MobileNavTab>
        )}

        <Menu>
          <button
            aria-label={t('nav.moreFromSuno')}
            className='px-3 py-2.5 text-foreground-primary'
            onClick={() => {
              // TODO: add new tracking on needs
              openMobileRootMenu();
            }}
          >
            <MoreHorizontalIcon className='h-6 w-6' />
          </button>
          <MobileMoreMenuModal
            isOpen={isMobileRootMenuOpen}
            onOpen={openMobileRootMenu}
            onClose={closeMobileRootMenu}
            onOpenFeedback={onOpenFeedback}
          />
        </Menu>
      </div>
    </div>
  );
};

const MobileTopBar: React.FC<{
  enableMobileSongPageV2?: boolean;
}> = observer(({ enableMobileSongPageV2 }) => {
  const { isSignedIn } = useAuth();
  const clerk = useClerk();
  const statsigClient = useStatsigClient();

  const { t } = useTranslation();

  const pathname = usePathname();
  const { search, session, notifications: notificationsStore } = useStores();
  const router = useRouter();
  const [isSearchExpanded, setIsSearchExpanded] = useState(false);
  const [isProfileMenuOpen, setIsProfileMenuOpen] = useState(false);

  const {
    isOpen: isWelcomeModalOpen,
    onOpen: onOpenWelcomeModal,
    onClose: onCloseWelcomeModal,
  } = useDisclosure();

  // Update global welcome modal state when local state changes
  useEffect(() => {
    session.setWelcomeModalOpen(isWelcomeModalOpen);
  }, [isWelcomeModalOpen, session]);

  const handleDismissClaimUsername = useCallback(async () => {
    try {
      await session.updateShownClaimUsername();
    } catch (error) {
      console.error('Failed to update shown_claim_username:', error);
    }
  }, [session]);

  const clearSearch = () => {
    search.searchTerm = '';
    if (searchInputRef.current) {
      searchInputRef.current.value = '';
      searchInputRef.current.focus();
    }
  };

  const searchInputRef = useRef<HTMLInputElement>(null);

  // focus on search input when it is shown
  useEffect(() => {
    searchInputRef?.current?.focus();
  }, []);

  useEffect(() => {
    session.getUserConfig();
  }, [session]);

  const toggleSearch = () => {
    setTimeout(() => searchInputRef?.current?.focus(), 0);
    setIsSearchExpanded((prevState) => {
      return !prevState;
    });
  };

  const {
    isOpen: isNotificationsPanelOpen,
    onOpen: openNotificationsPanel,
    onClose: closeNotificationsPanel,
  } = useDisclosure();

  const profileMenuRef = useRef<HTMLDivElement>(null);
  const isSongPage = pathname.startsWith('/song/');

  const isLiveRadio = isLiveRadioPath(pathname);

  // Skip the profile tooltip - let WelcomeModal handle profile completion flow
  let showClaimUserName = false;

  // Show claim username tooltip for users with incomplete profiles

  const isVip = statsigClient.checkGate('vip-profile-aura');

  const vipStyle = {
    backgroundImage:
      'linear-gradient(to bottom, rgba(13,8,8,0.2) 0%, rgba(13,8,8,1) 100%), url(https://cdn-o.suno.com/auras-v2/aura_vip.jpg)',
    backgroundSize: 'cover',
    backgroundPosition: 'top',
  };

  let clerkRedirectOptions: Record<string, string> = {
    [REFERRER_PARAM]: pathname,
    [SIGNUP_SOURCE_PARAM]: getSignUpSource(pathname),
  };

  if (enableMobileSongPageV2 && isSongPage) {
    clerkRedirectOptions = {
      ...clerkRedirectOptions,
      [SIGNUP_SOURCE_PARAM]: SIGNUP_SOURCE_VALUES.MOBILE_SONG_PAGE,
    };
  }

  return (
    <div
      className={clsx(
        '@container sticky top-0 flex items-center',
        'h-[60px] min-h-[60px] w-full',
        'gap-1 px-1',
        `z-[1000]`,
        'overflow-x-auto overflow-y-hidden',
        !isLiveRadio && 'bg-background-primary'
      )}
      style={isVip ? vipStyle : undefined}
    >
      <div className='min-w-4rem h-full grow px-1 ps-2 @sm:px-2 @md:px-3'>
        <Logo className='h-full w-20 max-w-full @sm:w-26' />
      </div>
      {isSignedIn && !session.sub?.plan && (
        <div className={'hidden @xs:block'}>
          <Button
            variant={ButtonVariant.Standard}
            shape={ButtonShape.Pill}
            size={ButtonSize.Small}
            className={
              session.credits <= 10
                ? 'bg-white text-foreground-primary-on-light'
                : ''
            }
            href='/account'
          >
            {t('nav.subscribe')}
          </Button>
        </div>
      )}
      <div
        className={clsx({
          relative: !isSearchExpanded,
          'absolute inset-1.5 rounded-full bg-tertiary p-2': isSearchExpanded,
          hidden: !isSignedIn,
          [`z-[10000]`]: isSearchExpanded,
        })}
      >
        <input
          className={clsx(
            'absolute inset-0 h-full w-full rounded-full border-none p-4 pr-[80px] outline-none',
            'bg-transparent placeholder-white/50',
            {
              block: !isSearchExpanded,
              hidden: !isSearchExpanded,
            }
          )}
          ref={searchInputRef}
          defaultValue={search.searchTerm}
          placeholder={
            session.flags?.['persona-search']
              ? 'Search for songs, playlists, users, or Personas'
              : 'Search for songs, playlists, or users'
          }
          onChange={(e) => {
            if (searchTimeout != null) {
              clearTimeout(searchTimeout);
              searchTimeout = null;
            }
            searchTimeout = setTimeout(() => {
              search.searchTerm = e.target.value;
              router.push('/search');
            }, 500);
          }}
        />
        <div
          className={clsx({
            'absolute inset-y-0 right-1 flex flex-row items-center justify-end gap-2':
              isSearchExpanded,
          })}
        >
          {isSearchExpanded && (
            <Button
              className={clsx({
                hidden: !(search.searchTerm && isSearchExpanded),
              })}
              variant={ButtonVariant.Tertiary}
              active={false}
              shape={ButtonShape.Pill}
              size={ButtonSize.Small}
              aria-label='Clear search'
              icon={CloseIcon}
              onClick={clearSearch}
            />
          )}
          <Button
            variant={ButtonVariant.Standard}
            shape={ButtonShape.Pill}
            size={ButtonSize.Small}
            aria-label={t('nav.search')}
            icon={SearchIcon}
            onClick={toggleSearch}
          />
        </div>
      </div>
      {isSignedIn && (
        <MediaQueryOnly
          mediaQuery={`(max-width: ${TAILWIND_MEDIUM_MIN_WIDTH - 1}px)`}
        >
          <div className='relative'>
            <Button
              variant={ButtonVariant.Standard}
              shape={ButtonShape.Pill}
              size={ButtonSize.Small}
              aria-label={t('nav.notifications')}
              icon={NotificationsIcon}
              onClick={() => {
                notificationsStore.loadNotifications();
                openNotificationsPanel();
                logWebUserEvent({
                  actionName: 'NotificationListOpened',
                  context: {
                    unreadCount: notificationsStore.unreadCount,
                    isMobile: true,
                  },
                });
              }}
            />
            {notificationsStore.unreadCount > 0 && (
              <NotificationDot className='absolute top-0 right-0 h-3 w-3 animate-pop-in border border-background-primary' />
            )}
          </div>
          <Modal
            isOpen={isNotificationsPanelOpen}
            onClose={() => {
              closeNotificationsPanel();
              logWebUserEvent({
                actionName: 'NotificationListClosed',
                context: {
                  unreadCount: notificationsStore.unreadCount,
                  isMobile: true,
                },
              });
            }}
            size='full'
            isCentered
          >
            <ModalOverlay sx={{ bgColor: colorVar('background/primary') }} />
            <ModalContent
              sx={{ bgColor: colorVar('background/primary') }}
              marginY='auto'
            >
              <div className='absolute top-2 right-2'>
                <CloseButton
                  onClick={(e) => {
                    // Do not mark as read if hodling shift key
                    if (!e.shiftKey) {
                      notificationsStore.markAllAsRead();
                    }
                    closeNotificationsPanel();
                    logWebUserEvent({
                      actionName: 'NotificationListClosed',
                      context: {
                        unreadCount: notificationsStore.unreadCount,
                        isMobile: true,
                      },
                    });
                  }}
                />
              </div>
              <ModalBody
                sx={{ bgColor: colorVar('background/primary') }}
                overflowY='auto'
                paddingX={0}
              >
                <h2 className='px-6 py-2 font-sans text-lg font-medium text-foreground-primary'>
                  {t('nav.notifications')}
                </h2>
                <div>
                  <NotificationList
                    currentTime={notificationsStore.notifiedAt}
                    notifications={notificationsStore.allNotifications}
                    isLoading={notificationsStore.isLoading}
                    hasMore={notificationsStore.hasMore}
                    onLoadMore={() =>
                      notificationsStore.loadMoreNotifications()
                    }
                    onDotClick={(payload) => {
                      notificationsStore.markAsRead(payload.id);
                      logWebUserEvent({
                        actionName: 'NotificationItemClicked',
                        context: {
                          notificationId: payload.id,
                          notificationType: payload.type || 'unknown',
                          clickTarget: 'dot',
                          isRead: false,
                          isMobile: true,
                        },
                      });
                    }}
                    onProfileClick={(payload, e) => {
                      // Do not mark as read if opening in new tav
                      if (!e || !(e.shiftKey || e.ctrlKey || e.metaKey)) {
                        notificationsStore.markAsRead(payload.id);
                        closeNotificationsPanel();
                      }
                      logWebUserEvent({
                        actionName: 'NotificationItemClicked',
                        context: {
                          notificationId: payload.id,
                          notificationType: payload.type || 'unknown',
                          clickTarget: payload.context || 'unknown',
                          isRead: payload.isRead,
                          isMobile: true,
                        },
                      });
                    }}
                    onContentClick={(payload, e) => {
                      // Do not mark as read if opening in new tav
                      if (!e || !(e.shiftKey || e.ctrlKey || e.metaKey)) {
                        notificationsStore.markAsRead(payload.id);
                        closeNotificationsPanel();
                      }
                      logWebUserEvent({
                        actionName: 'NotificationItemClicked',
                        context: {
                          notificationId: payload.id,
                          notificationType: payload.type || 'unknown',
                          clickTarget: 'content',
                          contentId: payload.contentId,
                          contentType: payload.contentType,
                          isRead: payload.isRead,
                          isMobile: true,
                        },
                      });
                    }}
                    onFollowClick={(payload, e) => {
                      // Do not mark as read if holding shift key
                      if (!e || !e.shiftKey) {
                        notificationsStore.markAsRead(payload.id);
                      }
                      notificationsStore.setFollowing(
                        payload.handle,
                        !payload.isFollowing
                      );
                      logWebUserEvent({
                        actionName: 'NotificationItemClicked',
                        context: {
                          notificationId: payload.id,
                          notificationType: payload.type || 'unknown',
                          clickTarget: payload.isFollowing
                            ? 'unfollow_button'
                            : 'follow_button',
                          isRead: payload.isRead,
                          isMobile: true,
                        },
                      });
                    }}
                    onNotificationView={(payload) => {
                      logWebUserEvent({
                        actionName: 'NotificationItemViewed',
                        context: {
                          notificationId: payload.id,
                          notificationType: payload.type || 'unknown',
                          isRead: payload.isRead,
                          isMobile: true,
                        },
                      });
                    }}
                  />
                </div>
              </ModalBody>
            </ModalContent>
          </Modal>
        </MediaQueryOnly>
      )}
      {isSignedIn ? (
        <>
          <div ref={profileMenuRef}>
            <ProfileMenu
              isOpen={isProfileMenuOpen}
              onClose={() => setIsProfileMenuOpen(false)}
              onToggle={() => {
                if (showClaimUserName) {
                  handleDismissClaimUsername();
                  onOpenWelcomeModal();
                  return;
                }
                setIsProfileMenuOpen((prev) => !prev);
              }}
            />
          </div>
          {showClaimUserName && (
            <CompleteProfileTooltip
              btnRef={profileMenuRef}
              handleDismissClaimUsername={handleDismissClaimUsername}
              onOpenWelcomeModal={onOpenWelcomeModal}
              isMobile={true}
            />
          )}
        </>
      ) : (
        <div className='whitespace-nowrap'>
          <Button
            variant={ButtonVariant.Primary}
            icon={<ArrowRightIcon />}
            onClick={() => {
              logWebUserEvent({
                actionName: 'NavbarMobileSignInButtonClicked',
                context: {
                  pathname: pathname,
                },
              });

              clerk.openSignIn({
                withSignUp: true,
                ...getClerkSignInRedirectProps(pathname, clerkRedirectOptions),
              });
            }}
          >
            {t('nav.signIn')}
          </Button>
        </div>
      )}
      {isWelcomeModalOpen && (
        <WelcomeModal
          isOpen={isWelcomeModalOpen}
          onClose={() => {
            onCloseWelcomeModal();
            handleDismissClaimUsername();
          }}
          reclaim={true}
        />
      )}
    </div>
  );
});

export default MobileTopBar;
