'use client';

import {
  IconButton,
  Link,
  Menu,
  MenuButton,
  MenuItem,
  MenuList,
  Portal,
} from '@chakra-ui/react';
import { useClerk } from '@clerk/nextjs';
import { useGateValue, useLayer } from '@statsig/react-bindings';
import { observer } from 'mobx-react-lite';

import { useStores } from '@/app/(root)/AppProviders';
import ImageWithFallback from '@/components/image/ImageWithFallback';
import NextLink from '@/components/link/Link';
import ProfileEditModal from '@/components/modal/ProfileEditModal';
import { ModalTypes } from '@/components/modal/constants/ModalTypes';
import { useModalContext } from '@/context/ModalContext';
import useDisclosure from '@/hooks/useDisclosure';
import { clearSunoSessionId, useApiClient } from '@/lib/apiClient';
import logWebUserEvent, { logoutUser } from '@/logging/logWebUserEvent';
import { FALLBACK_IMAGE_URL, TOP_MENUS_SUPER_Z_INDEX } from '@/utils/constants';

import ThemeSelectorDropdown from '../login/ThemeSelectorDropdown';
import { ArtistProfileForm } from '../profile/ArtistProfileForm';

interface ProfileMenuComponentProps {
  isOpen: boolean;
  onClose: () => void;
  onToggle: () => void;
}

const ProfileMenu: React.FC<ProfileMenuComponentProps> = observer(
  ({
    isOpen,
    onClose,
    onToggle,
  }: {
    isOpen: boolean;
    onClose: () => void;
    onToggle: () => void;
  }) => {
    const { session } = useStores();
    const clerk = useClerk();
    const apiClient = useApiClient();
    const {
      onOpen: onOpenEditProfile,
      isOpen: isOpenEditProfile,
      onClose: onCloseEditProfile,
    } = useDisclosure();

    const { openModal } = useModalContext();

    const {
      isOpen: isProfileEditModalOpen,
      onOpen: onOpenProfileEditModal,
      onClose: onCloseProfileEditModal,
    } = useDisclosure();

    const authLayer = useLayer('auth-layer');
    const isClerklessAuthEnabled = authLayer.get(
      'is_clerkless_auth_enabled',
      false
    );
    const isManageAccountHidden = useGateValue('web-hide-manage-account');
    const enableManageAccount =
      !isClerklessAuthEnabled && !isManageAccountHidden;
    const enableThemeSelector = useGateValue('web-theme-selector');

    const handleEditProfile = () => {
      if (session.flags?.['artist-profiles']) {
        onOpenProfileEditModal();
        logWebUserEvent(
          {
            actionName: 'ArtistProfileEditButtonClicked',
            context: {
              source: 'mobile-menu',
            },
          },
          session
        );
      } else {
        onOpenEditProfile();
      }
    };

    return (
      <>
        <Menu isOpen={isOpen} onClose={onClose}>
          <MenuButton
            as={IconButton}
            variant='ghost'
            color='whiteAlpha'
            onClick={onToggle}
            icon={
              <ImageWithFallback
                className='size-9 rounded-full'
                src={session.user?.avatar_image_url || FALLBACK_IMAGE_URL}
                alt='User Profile'
              />
            }
            colorScheme='whiteAlpha'
            aria-label='User Profile'
            _hover={{ backgroundColor: 'none' }}
          />
          <Portal>
            <MenuList
              sx={{
                bgColor: 'var(--color-background-secondary)',
                color: 'var(--color-foreground-primary)',
              }}
              borderColor='rgba(255, 255, 255, 0.1)'
              w='250px'
              p='2'
              borderRadius='md'
              zIndex={TOP_MENUS_SUPER_Z_INDEX}
            >
              <div className='flex flex-row py-2'>
                <ImageWithFallback
                  className='mr-4 ml-2 size-10 rounded-full'
                  src={session.user?.avatar_image_url || FALLBACK_IMAGE_URL}
                  alt='Profile Image'
                />

                <div className='mr-4 flex max-w-[150px] flex-col justify-center gap-1'>
                  {!!session.user?.display_name && (
                    <p
                      className='line-clamp-1 font-sans text-[14px] leading-[18px] font-bold'
                      title={session.user?.display_name}
                    >
                      {session.user?.display_name}
                    </p>
                  )}
                  <p
                    className='font-sans text-[12px] leading-[12px]'
                    title={clerk.user?.emailAddresses?.[0]?.emailAddress}
                  >
                    {clerk.user?.emailAddresses?.[0]?.emailAddress || ''}
                  </p>
                </div>
              </div>
              <MenuItem
                as={NextLink}
                href={`/@${session.user?.handle}`}
                fontFamily={'Neue Montreal'}
                sx={{
                  bg: 'transparent',
                  _hover: {
                    bg: 'rgba(255, 255, 255, 0.1)',
                  },
                  transition: 'background-color 0.3s ease',
                  borderRadius: '6px',
                  outline: 'none',
                }}
              >
                View Profile
              </MenuItem>
              <MenuItem
                as={Link}
                onClick={handleEditProfile}
                fontFamily={'Neue Montreal'}
                sx={{
                  bg: 'transparent',
                  _hover: {
                    bg: 'rgba(255, 255, 255, 0.1)',
                    textDecoration: 'none',
                  },
                  transition: 'background-color 0.3s ease',
                  borderRadius: '6px',
                  outline: 'none',
                }}
              >
                Edit Profile
              </MenuItem>
              <MenuItem
                as={Link}
                onClick={(e) => {
                  e.preventDefault();
                  openModal(ModalTypes.INVITE_FRIEND, 'ProfileMenu');
                }}
                fontFamily={'Neue Montreal'}
                sx={{
                  bg: 'transparent',
                  _hover: {
                    bg: 'rgba(255, 255, 255, 0.1)',
                    textDecoration: 'none',
                  },
                  transition: 'background-color 0.3s ease',
                  borderRadius: '6px',
                  outline: 'none',
                }}
              >
                Invite Friends
              </MenuItem>

              <MenuItem
                as={NextLink}
                href='/account'
                onClick={onClose}
                fontFamily={'Neue Montreal'}
                sx={{
                  bg: 'transparent',
                  _hover: {
                    bg: 'rgba(255, 255, 255, 0.1)',
                  },
                  transition: 'background-color 0.3s ease',
                  borderRadius: '6px',
                  outline: 'none',
                }}
              >
                Subscription
                <div className='ml-4'>
                  <div
                    className='flex items-center justify-center rounded-full px-1 py-0.5'
                    style={{
                      backgroundColor:
                        session.credits > 0 ? '#272626' : '#fcd28d',
                      color: session.credits > 0 ? 'white' : 'black',
                    }}
                  >
                    <span className='font-sans text-[11px] font-bold'>
                      {session.credits.toLocaleString()} credits
                    </span>
                  </div>
                </div>
              </MenuItem>
              {enableManageAccount && (
                <MenuItem
                  as={Link}
                  onClick={() =>
                    clerk.openUserProfile({
                      appearance: {
                        elements: {
                          modalContent: {
                            height: 'auto',
                          },
                          cardBox: {
                            height: '20rem',
                          },
                          profileSection__profile: {
                            display: 'none',
                          },
                          button:
                            'text-foreground-primary hover:text-foreground-secondary',
                          badge:
                            'text-foreground-primary outline outline-foreground-primary',
                        },
                      },
                    })
                  }
                  fontFamily={'Neue Montreal'}
                  sx={{
                    bg: 'transparent',
                    _hover: {
                      bg: 'rgba(255, 255, 255, 0.1)',
                      textDecoration: 'none',
                    },
                    transition: 'background-color 0.3s ease',
                    borderRadius: '6px',
                    outline: 'none',
                  }}
                >
                  Manage Account
                </MenuItem>
              )}
              {enableThemeSelector && <ThemeSelectorDropdown />}
              <MenuItem
                as={Link}
                onClick={() => {
                  logoutUser();
                  logWebUserEvent({
                    actionName: 'SignOutButtonClicked',
                  });
                  apiClient.POST('/api/signout/', {});
                  clerk
                    .signOut({
                      redirectUrl: '/',
                    })
                    .then(() => {
                      clearSunoSessionId();
                      session.loadSession({ retries: 1, forceLoad: true });
                    });
                }}
                fontFamily={'Neue Montreal'}
                sx={{
                  bg: 'transparent',
                  _hover: {
                    bg: 'rgba(255, 255, 255, 0.1)',
                    textDecoration: 'none',
                  },
                  transition: 'background-color 0.3s ease',
                  borderRadius: '6px',
                  outline: 'none',
                }}
              >
                Sign Out
              </MenuItem>
            </MenuList>
          </Portal>
        </Menu>
        <ArtistProfileForm
          isOpen={isOpenEditProfile}
          onClose={onCloseEditProfile}
          data-qaid='modal-edit-profile-title'
        />
        <ProfileEditModal
          isOpen={isProfileEditModalOpen}
          onClose={onCloseProfileEditModal}
          artistProfileInfo={session.artistProfileInfo}
          onArtistProfileInfoUpdate={(updatedInfo) => {
            session.updateArtistProfileInfo(updatedInfo);
          }}
          onSuccess={() => {
            // Profile updated successfully
          }}
        />
      </>
    );
  }
);

export default ProfileMenu;
