import { Fragment, useEffect } from 'react';

import { useModal } from '@material-hu/hooks/useModal';
import Box from '@material-hu/mui/Box';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import Dialog from '@material-hu/components/design-system/Dialog';

import { useAuth } from 'src/contexts/JWTContext';
import useHuGoTheme from 'src/hooks/useHuGoTheme';
import useLocalStorage from 'src/hooks/useLocalStorage';
import useThemeMode from 'src/hooks/useThemeMode';
import { useLokaliseTranslation } from 'src/utils/i18n';

import AppearanceSection from '../navbar/components/AppearanceSection';

const STORAGE_KEY_PREFIX = 'hu_dark_mode_announced_';

const DarkModeAnnouncement = () => {
  const { t } = useLokaliseTranslation('settings');
  const { user } = useAuth();
  const { commitThemeMode, resetThemeMode } = useThemeMode();
  const HugoThemeProvider = useHuGoTheme();

  const [announced, setAnnounced] = useLocalStorage<boolean>(
    `${STORAGE_KEY_PREFIX}${user?.id}`,
    false,
  );

  const handleClose = () => {
    // Dismiss without applying: discard the previewed theme.
    resetThemeMode();
    setAnnounced(true);
    closeModal();
  };

  const handleSave = () => {
    // Persist the theme picked in the modal.
    commitThemeMode();
    setAnnounced(true);
    closeModal();
  };

  // Split the body on the "preferences" word so it can be rendered in semibold,
  // matching the design (the rest stays regular weight).
  const preferencesWord = t('preferences');
  const bodyParts = t('dark_mode_announcement_body').split(preferencesWord);

  const { modal, showModal, closeModal } = useModal(
    () => (
      <Dialog
        title={t('dark_mode_announcement_title')}
        onClose={handleClose}
        body={
          <Stack sx={{ gap: 2 }}>
            <Typography variant="globalS">
              {bodyParts.map((part, index) => (
                // biome-ignore lint/suspicious/noArrayIndexKey: static split, order is stable
                <Fragment key={index}>
                  {part}
                  {index < bodyParts.length - 1 && (
                    <Box
                      component="strong"
                      sx={{ fontWeight: 'fontWeightSemiBold' }}
                    >
                      {preferencesWord}
                    </Box>
                  )}
                </Fragment>
              ))}
            </Typography>
            <AppearanceSection bare />
          </Stack>
        }
        primaryButtonProps={{
          children: t('dark_mode_announcement_cta'),
          onClick: handleSave,
        }}
      />
    ),
    // Route backdrop click / Escape through handleClose too, so closing by any
    // path discards the previewed theme (the X button uses onClose above).
    { fullWidth: true, maxWidth: 'sm', onClose: handleClose },
  );

  useEffect(() => {
    if (user?.id && !announced) {
      showModal();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [user?.id, announced, showModal]);

  return <HugoThemeProvider>{modal}</HugoThemeProvider>;
};

export default DarkModeAnnouncement;
