import { FC, useEffect, useState } from 'react';

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

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

import shiftsCoachmarkImageModal from 'src/assets/svg/shifts_coachmark.svg';
import shiftsCoachmarkImageS1 from 'src/assets/images/shifts_coachmark_s1.webp';
import shiftsCoachmarkImageS2 from 'src/assets/images/shifts_coachmark_s2.webp';
import shiftsCoachmarkImageS3 from 'src/assets/images/shifts_coachmark_s3.webp';
import { useAuth } from 'src/contexts/JWTContext';
import useHuGoTheme from 'src/hooks/useHuGoTheme';

import { useLokaliseTranslation } from 'src/utils/i18n';
import { getClientOs } from 'src/utils/platform';
import { modifierKey } from 'src/utils/keyboardShortcuts';

import { COACHMARK_ELEMENT_IDS } from './constants';
import { useShiftsCoachmark } from './ShiftsCoachmarkContext';

/**
 * Shifts coachmark component that handles the full onboarding flow:
 * 1. Intro modal explaining the feature
 * 2. HuCoachmark tour pointing to UI elements
 */
const ShiftsCoachmark: FC = () => {
  const HuGoThemeProvider = useHuGoTheme();
  const { t } = useLokaliseTranslation(['shifts']);
  const { user } = useAuth();

  const isMacOS = getClientOs() === 'MacOS';

  const {
    startTour,
    handleCoachmarkClose,
    setCurrentStep,
    currentStep,
    hasCompletedCoachmark,
    openStep3Menu,
  } = useShiftsCoachmark();

  // Intro modal
  const introModal = useModal(
    () => (
      <HuDialog
        onClose={() => {
          introModal.closeModal();
          startTour();
        }}
        title={t('shifts:coachmark.modal_header')}
        body={
          <Stack sx={{ alignItems: 'center', gap: 2 }}>
            <img
              src={shiftsCoachmarkImageModal}
              alt=""
              style={{ height: 'auto' }}
            />
            <Stack sx={{ alignItems: 'center' }}>
              <Typography
                variant="globalM"
                sx={{ fontWeight: 'fontWeightSemiBold' }}
              >
                {t('shifts:coachmark.modal_title')}
              </Typography>
              <Typography
                variant="globalS"
                sx={{
                  textAlign: 'center',
                  color: theme => theme.palette.new.text.neutral.lighter,
                }}
              >
                {t('shifts:coachmark.modal_description', {
                  key: modifierKey(),
                })}
              </Typography>
            </Stack>
          </Stack>
        }
        primaryButtonProps={{
          children: t('general:understood'),
          onClick: () => {
            introModal.closeModal();
            startTour();
          },
        }}
      />
    ),
    {
      maxWidth: false,
      PaperProps: {
        sx: {
          width: 540,
          maxHeight: 'none',
          '& .MuiDialogContent-root': {
            overflow: 'visible',
            paddingTop: 0,
          },
        },
      },
    },
  );

  // Show intro modal when phase is 'intro'
  useEffect(() => {
    if (!hasCompletedCoachmark) {
      introModal.showModal();
    }
  }, []);

  // Unique coachmark ID per user
  const coachmarkId = `shifts-coachmark-${user?.id}`;

  // Render coachmark while not completed
  const shouldRenderCoachmark = !hasCompletedCoachmark && currentStep >= 1;

  // State for step 3 ref
  const [step3Ref, setStep3Ref] = useState<HTMLElement | null>(null);

  // Open menu and get ref when reaching step 3
  useEffect(() => {
    if (currentStep === 3) {
      openStep3Menu().then(element => {
        setStep3Ref(element);
      });
    } else {
      setStep3Ref(null);
    }
  }, [currentStep, openStep3Menu]);

  const steps = shouldRenderCoachmark
    ? [
        {
          ref: document.getElementById(COACHMARK_ELEMENT_IDS.firstShift),
          image: shiftsCoachmarkImageS1,
          title: t('shifts:coachmark.step1_title'),
          description: t('shifts:coachmark.step1_description'),
          placement: 'right' as const,
        },
        {
          ref: document.getElementById(COACHMARK_ELEMENT_IDS.emptyCell),
          image: shiftsCoachmarkImageS2,
          title: t('shifts:coachmark.step2_title'),
          description: t('shifts:coachmark.step2_description'),
          placement: 'right' as const,
        },
        {
          ref: step3Ref,
          image: shiftsCoachmarkImageS3,
          title: t('shifts:coachmark.step3_title'),
          description: t('shifts:coachmark.step3_description', {
            key: isMacOS ? 'Cmd' : 'Ctrl',
          }),
          placement: 'left-start' as const,
        },
      ]
    : [];

  return (
    <>
      {introModal.modal}

      {shouldRenderCoachmark && (
        <HuGoThemeProvider>
          <HuCoachmark
            id={coachmarkId}
            steps={steps}
            hideFooterOnOnlyOneStep={false}
            finishOnClose
            onClose={handleCoachmarkClose}
            onStepChange={setCurrentStep}
          />
        </HuGoThemeProvider>
      )}
    </>
  );
};

export default ShiftsCoachmark;

// Re-exports
export {
  COACHMARK_ELEMENT_IDS,
  COACHMARK_MOCK_SHIFT_ID,
  COACHMARK_MOCK_USER_ID,
  generateCoachmarkMockData,
} from './constants';
export {
  useShiftsCoachmark,
  ShiftsCoachmarkProvider,
} from './ShiftsCoachmarkContext';
