import React, {
  useState, useEffect, useMemo, useCallback,
} from 'react';
import isEmpty from 'lodash/isEmpty';
import CapIcon from '@capillarytech/cap-ui-library/CapIcon';
import messages from '../messages';
import { STEPS, INAPP_EDITOR_TYPES } from '../constants';

/**
 * Custom hook to handle InAppWrapper component business logic
 */
const useInAppWrapper = ({
  intl: { formatMessage },
  onInAppEditorTypeChange,
  inAppEditorType,
  step,
  showNextStep,
  onResetStep,
  onEnterTemplateName,
  onRemoveTemplateName,
  // Props for InApp component
  setIsLoadingContent,
  isGetFormData,
  getFormdata,
  type,
  isFullMode,
  cap,
  showTemplateName,
  showLiquidErrorInFooter,
  onValidationFail,
  forwardedTags,
  selectedOfferDetails,
  onPreviewContentClicked,
  onTestContentClicked,
  eventContextTags,
  onCreateComplete,
  handleClose,
  templateData,
  getDefaultTags,
}) => {
  // State management
  const [templateName, setTemplateName] = useState('');
  const [isTemplateNameEmpty, setIsTemplateNameEmpty] = useState(true);
  const [selectedEditorType, setSelectedEditorType] = useState('');
  const [routeParams] = useState({
    pathname: `/inapp/create`,
    query: { module: 'library', type: 'embedded' },
  });

  // Cleanup effect
  useEffect(() => () => {
    onResetStep();
  }, [onResetStep]);

  // Event handlers
  const onTemplateNameChange = useCallback(({target: {value}}) => {
    const isEmptyTemplateName = !value?.trim();
    setTemplateName(value);
    setIsTemplateNameEmpty(isEmptyTemplateName);

    if (value && onEnterTemplateName) {
      onEnterTemplateName();
    } else if (onRemoveTemplateName) {
      onRemoveTemplateName();
    }
  }, [onEnterTemplateName, onRemoveTemplateName]);

  const onChange = useCallback((e) => {
    onInAppEditorTypeChange(e.target.value);
  }, [onInAppEditorTypeChange]);

  const handleEditorTypeSelection = useCallback(() => {
    if (inAppEditorType && !isTemplateNameEmpty) {
      setSelectedEditorType(inAppEditorType);
      showNextStep();
    }
  }, [inAppEditorType, isTemplateNameEmpty, showNextStep]);

  // Main logic effect
  useEffect(() => {
    // Skip if user has already made a selection
    if (selectedEditorType) return;

    // Handle different steps
    switch (step) {
      case STEPS.MODE_SELECTION:
        // Wait for user to select editor type and enter template name
        break;

      case STEPS.CREATE_TEMPLATE_CONTENT:
        if (inAppEditorType) {
          setSelectedEditorType(inAppEditorType);
        }
        break;

      default:
        // No operation for other steps
        break;
    }
  }, [
    step,
    selectedEditorType,
    inAppEditorType,
  ]);

  // Derived state
  const isShowInAppCreate = !isEmpty(selectedEditorType) && inAppEditorType;

  // Memoize static data
  const modes = useMemo(() => [
    {
      title: formatMessage(messages.htmlEditor),
      content: formatMessage(messages.htmlEditorDesc),
      value: INAPP_EDITOR_TYPES.HTML_EDITOR,
      icon: <CapIcon type="code" />,
    },
    {
      title: formatMessage(messages.dragDropEditor),
      content: formatMessage(messages.dragDropEditorDesc),
      value: INAPP_EDITOR_TYPES.DRAG_DROP_EDITOR,
      icon: <CapIcon type="draggable" />,
    },
  ], [formatMessage]);

  // Prepare props for InApp component
  const inAppProps = useMemo(() => {
    const props = {
      setIsLoadingContent,
      key: "inapp-create-template",
      location: routeParams,
      route: { name: 'inapp' },
      params: {},
      isGetFormData,
      getFormData: getFormdata, // Map getFormdata to getFormData (matching InApp component prop name)
      getFormSubscriptionData: getFormdata,
      getDefaultTags: type || getDefaultTags,
      isFullMode,
      defaultData: {
        'template-name': templateName,
        'editor-type': inAppEditorType, // Pass editor type to InApp component
      },
      templateData,
      cap,
      showTemplateName,
      showLiquidErrorInFooter,
      onValidationFail,
      forwardedTags,
      selectedOfferDetails,
      onPreviewContentClicked,
      onTestContentClicked,
      eventContextTags,
      onCreateComplete,
      handleClose,
    };
    return props;
  }, [
    setIsLoadingContent,
    routeParams,
    isGetFormData,
    getFormdata,
    type,
    getDefaultTags,
    isFullMode,
    templateName,
    inAppEditorType,
    templateData,
    cap,
    showTemplateName,
    showLiquidErrorInFooter,
    onValidationFail,
    forwardedTags,
    selectedOfferDetails,
    onPreviewContentClicked,
    onTestContentClicked,
    eventContextTags,
    onCreateComplete,
    handleClose,
  ]);

  return {
    // State
    templateName,
    isTemplateNameEmpty,
    selectedEditorType,

    // Derived values
    modes,
    isShowInAppCreate,
    inAppProps,

    // Event handlers
    onTemplateNameChange,
    onChange,
    handleEditorTypeSelection,
  };
};

export default useInAppWrapper;
