import { type FC, useMemo } from 'react';

import HuCoachmark from '@material-hu/components/design-system/Coachmark';
import { type CoachMarkStepWithRef } from '@material-hu/components/design-system/Coachmark/types';

import smApprovalFilterCoachmark from 'src/assets/images/sm_approval_filter_coachmark.svg';
import smApprovalSearchCoachmark from 'src/assets/images/sm_approval_search_coachmark.svg';
import { useAuth } from 'src/contexts/JWTContext';
import useLocalStorage from 'src/hooks/useLocalStorage';
import { useLokaliseTranslation } from 'src/utils/i18n';

type ApprovalsCoachmarkProps = {
  searchAnchor: HTMLElement | null;
  filterAnchor: HTMLElement | null;
  /** Suffix used to keep the agent workspace and portal coachmarks tracked independently. */
  storageKeySuffix: string;
};

const ApprovalsCoachmark: FC<ApprovalsCoachmarkProps> = ({
  searchAnchor,
  filterAnchor,
  storageKeySuffix,
}) => {
  const { t } = useLokaliseTranslation('service_management');
  const { user } = useAuth();

  const storageKey = `service-management-approvals-coachmark-${storageKeySuffix}-${user?.id}`;
  const [hasCompletedCoachmark, setHasCompletedCoachmark] =
    useLocalStorage<boolean>(storageKey, false);

  const steps = useMemo<CoachMarkStepWithRef[]>(
    () => [
      {
        ref: searchAnchor,
        image: smApprovalSearchCoachmark,
        title: t('approvals.coachmark_search_title'),
        description: t('approvals.coachmark_search_description'),
        placement: 'bottom',
      },
      {
        ref: filterAnchor,
        image: smApprovalFilterCoachmark,
        title: t('approvals.coachmark_filter_title'),
        description: t('approvals.coachmark_filter_description'),
        placement: 'bottom',
      },
    ],
    [searchAnchor, filterAnchor, t],
  );

  if (hasCompletedCoachmark || !searchAnchor || !filterAnchor) {
    return null;
  }

  return (
    <HuCoachmark
      id={storageKey}
      steps={steps}
      hideFooterOnOnlyOneStep={false}
      finishOnClose
      onClose={() => setHasCompletedCoachmark(true)}
    />
  );
};

export default ApprovalsCoachmark;
