import {memo, useCallback, useEffect, useMemo, useState} from 'react';
import {useTranslation} from 'react-i18next';
import {Coachmark} from '@components';
import {CHATS_LOCAL_STORAGE_KEYS} from '@modules/chats/constants';
import {useIsConversationsLoading} from '@modules/chats/store';
import {setItemFromStorageSync} from '@services/localStorage';

import {getFeatureModalSteps} from './utils';

function ChatModalFeaturesComponent() {
  const {t} = useTranslation();
  const steps = useMemo(() => getFeatureModalSteps(), []);
  const hasNewFeatures = steps.length > 0;
  const isConversationsLoading = useIsConversationsLoading();
  const [isVisible, setIsVisible] = useState(false);

  const onCloseModal = useCallback(() => {
    setIsVisible(false);
    const lastFeature = steps.at(-1)?.key;

    if (lastFeature) {
      setItemFromStorageSync({
        key: CHATS_LOCAL_STORAGE_KEYS.LastFeatureShown,
        value: lastFeature,
        isObject: false,
      });
    }
  }, [steps]);

  useEffect(() => {
    if (hasNewFeatures && !isConversationsLoading) {
      // Run this on idle to avoid UI issues
      const idleId = requestIdleCallback(
        () => {
          setIsVisible(true);
        },
        {timeout: 1000},
      );
      return () => cancelIdleCallback(idleId);
    }
  }, [isConversationsLoading, hasNewFeatures]);

  // If this is no carousel - Header title is the step title;
  const dataToRender = useMemo(() => {
    if (steps.length === 1) {
      const step = steps[0];
      return {
        headerTitle: step.title,
        steps: [{...step, title: undefined}],
      };
    }
    return {
      headerTitle: t('chat.features.title'),
      steps,
    };
  }, [steps, t]);

  return hasNewFeatures ? (
    <Coachmark
      title={dataToRender.headerTitle}
      steps={dataToRender.steps}
      isVisible={isVisible}
      onClose={onCloseModal}
    />
  ) : null;
}

export const ChatModalFeatures = memo(ChatModalFeaturesComponent);
