import { type MouseEvent } from 'react';
import { useNavigate } from 'react-router-dom';

import '../i18n';

import {
  IconArrowBack,
  IconChevronRight,
  IconMessageChatbot,
  IconSettings,
  IconUser,
} from '@material-hu/icons/tabler';
import MenuList from '@material-hu/mui/MenuList';
import Stack from '@material-hu/mui/Stack';
import { useTheme } from '@material-hu/mui/styles';

import TextOverflowTip from '@material-hu/components/composed-components/TextOverflowTip';
import HuAvatar from '@material-hu/components/design-system/Avatar';
import Button from '@material-hu/components/design-system/Buttons/Button';
import ListItem from '@material-hu/components/design-system/List/components/ListItem';
import MenuItem from '@material-hu/components/design-system/Menu/components/MenuItem';
import useSnackbar from '@material-hu/components/design-system/Snackbar';
import HuTitle from '@material-hu/components/design-system/Title';

import { isDev } from 'src/constants/env';
import { useAuth } from 'src/contexts/JWTContext';
import { usePreferencesDrawer } from 'src/contexts/PreferencesDrawerContext';
import { useSettings } from 'src/contexts/SettingsContext';
import useGeneralError from 'src/hooks/useGeneralError';
import {
  useClearMoodMutation,
  useCurrentMoodQuery,
} from 'src/hooks/useUserMood';
import { profileRoutes } from 'src/pages/dashboard/profile/routes';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { getFullName, getInitials } from 'src/utils/userUtils';

import { useMoodStatusDrawer } from './MoodStatusDrawer/useMoodStatusDrawer';

const MOOD_PREVIEW_INSTANCE_ID = 2543;

const AccountPopoverContent = () => {
  const navigate = useNavigate();
  const { resetPrimary } = useSettings();
  const { user, logout, instance } = useAuth();
  const { openPreferencesDrawer } = usePreferencesDrawer();
  const showGeneralError = useGeneralError();
  const { t } = useLokaliseTranslation(['authentication', 'user_mood']);
  const theme = useTheme();

  // TODO(SQCY-2778): temporary gate so the feature can be previewed in a
  // single dev community (see MOOD_PREVIEW_INSTANCE_ID) while the
  // USER_MOOD_ENABLED community feature is wired up. Replace with
  // `useCommunityFeature(CommunityFeature.USER_MOOD_ENABLED)`.
  const canSetMood = isDev && instance?.id === MOOD_PREVIEW_INSTANCE_ID;

  const { openMoodDrawer } = useMoodStatusDrawer();
  const { enqueueSnackbar } = useSnackbar();
  const { data: mood } = useCurrentMoodQuery({ enabled: canSetMood });
  const { mutate: clearMoodMutate } = useClearMoodMutation();

  // Already gated by `enabled: canSetMood`, but kept defensive so a stale
  // cached value from a prior session can't leak into the menu either.
  const activeMood = canSetMood ? mood : null;

  const handleLogout = async (): Promise<void> => {
    try {
      await logout?.(true);
      resetPrimary();
      navigate('/');
      if (instance?.externalBotId) window.location.reload();
    } catch (err) {
      showGeneralError(err, t('LOGOUT_ERROR'));
    }
  };

  const handleGoToAccount = (e: MouseEvent<HTMLLIElement>) => {
    e.stopPropagation();
    navigate(profileRoutes.profile(user?.id ?? ''));
  };

  const handleOpenSettingsDrawer = (e: MouseEvent<HTMLLIElement>) => {
    e.stopPropagation();
    openPreferencesDrawer();
  };

  const handleOpenMoodDrawer = (e: MouseEvent<HTMLLIElement>) => {
    e.stopPropagation();
    openMoodDrawer();
  };

  const handleResetStatus = (e: MouseEvent<HTMLLIElement>) => {
    e.stopPropagation();
    clearMoodMutate(undefined, {
      onSuccess: () => {
        enqueueSnackbar({
          title: t('user_mood:clear_success'),
          variant: 'success',
        });
      },
    });
  };

  const userFullName = getFullName(user);

  return (
    <Stack sx={{ width: theme.spacing(35) }}>
      <Stack
        sx={{
          borderBottom: `1px solid ${theme.palette.new.border.neutral.default}`,
        }}
      >
        <Stack
          sx={{
            flexDirection: 'row',
            gap: 1,
            p: 2,
            alignItems: 'center',
          }}
        >
          <HuAvatar
            src={user?.profilePicture ?? ''}
            alt=""
            text={getInitials(userFullName)}
          />
          <Stack sx={{ flex: 1, minWidth: 0 }}>
            <HuTitle
              title={userFullName}
              variant="S"
            />
            <TextOverflowTip
              primary={
                activeMood?.description ?? user?.employeeInternalId ?? ''
              }
              slotProps={{
                typography: {
                  variant: 'globalXS',
                  sx: { color: theme.palette.new.text.neutral.lighter },
                },
              }}
            />
          </Stack>
          {activeMood && (
            <HuAvatar
              text={activeMood.emoji}
              size="small"
              sx={{
                ml: 'auto',
                '& .MuiTypography-root': {
                  fontSize: 20,
                  lineHeight: 1,
                },
              }}
            />
          )}
        </Stack>
        <MenuList disablePadding>
          {!!activeMood && (
            <MenuItem
              onClick={handleResetStatus}
              sx={{ p: 0 }}
            >
              <ListItem
                component="div"
                sx={{ width: '100%' }}
                divider
                avatar={{ Icon: IconArrowBack }}
                text={{ title: t('user_mood:reset_status') }}
                slotProps={{
                  container: { sx: { pr: 0, pl: 2, py: 1 } },
                }}
              />
            </MenuItem>
          )}
          {canSetMood && (
            <MenuItem
              onClick={handleOpenMoodDrawer}
              sx={{ p: 0 }}
            >
              <ListItem
                component="div"
                sx={{ width: '100%' }}
                avatar={{ Icon: IconMessageChatbot }}
                text={{ title: t('user_mood:update_status') }}
                action={{ Icon: IconChevronRight }}
                slotProps={{
                  container: { sx: { pr: 0.5, pl: 2, py: 1 } },
                }}
              />
            </MenuItem>
          )}
          <MenuItem
            onClick={handleGoToAccount}
            sx={{ p: 0 }}
          >
            <ListItem
              component="div"
              sx={{ width: '100%' }}
              avatar={{ Icon: IconUser }}
              text={{ title: t('SEE_PROFILE') }}
              action={{ Icon: IconChevronRight }}
              slotProps={{
                container: { sx: { pr: 0.5, pl: 2, py: 1 } },
              }}
            />
          </MenuItem>
          <MenuItem
            onClick={handleOpenSettingsDrawer}
            sx={{ p: 0 }}
          >
            <ListItem
              component="div"
              sx={{ width: '100%' }}
              avatar={{ Icon: IconSettings }}
              text={{ title: t('settings:preferences') }}
              action={{ Icon: IconChevronRight }}
              slotProps={{
                container: { sx: { pr: 0.5, pl: 2, py: 1 } },
              }}
            />
          </MenuItem>
        </MenuList>
      </Stack>
      <Stack sx={{ p: 2 }}>
        <Button
          size="small"
          variant="secondary"
          onClick={handleLogout}
        >
          {t('LOGOUT')}
        </Button>
      </Stack>
    </Stack>
  );
};

export default AccountPopoverContent;
