/**
 * Copyright 2024 Phenix Real Time Solutions, Inc. Confidential and Proprietary. All Rights Reserved.
 */

import React, {useState} from 'react';

import {Modal} from 'components/modal';

interface IMultiStepModal {
  isOpen: boolean;
  closeModal: () => void;
  steps: {
    title: string;
    component: React.JSX.Element;
    saveButton?: {
      onClick?: () => void;
      text?: string;
      disabled?: boolean;
      className?: string;
    };
    cancel?: () => void;
    cancelDisabled?: boolean;
  }[];
}

const MultiStepModal = ({isOpen, closeModal, steps}: IMultiStepModal): React.JSX.Element => {
  const [currentStep, setCurrentStep] = useState(0);
  const isLastStep = steps.length - 1 === currentStep;
  const saveButtonText = isLastStep ? 'Done' : 'Next';
  const handleCloseModal = () => {
    closeModal();
    setCurrentStep(0);
  };

  const handleSave = () => {
    if (steps[currentStep]?.saveButton?.onClick) {
      steps[currentStep].saveButton.onClick();
    }

    if (isLastStep) {
      handleCloseModal();
    } else {
      setCurrentStep(currentStep + 1);
    }
  };

  if (isOpen) {
    return (
      <Modal
        close={handleCloseModal}
        submitButton={{
          className: steps[currentStep]?.saveButton?.className,
          disabled: steps[currentStep]?.saveButton?.disabled,
          onClick: handleSave,
          label: steps[currentStep]?.saveButton?.text || saveButtonText
        }}
        cancelButton={{disabled: steps[currentStep]?.cancelDisabled}}>
        {steps[currentStep]?.component || null}
      </Modal>
    );
  }

  return null;
};

export default MultiStepModal;
