import React, {
  useEffect,
  useLayoutEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import { __ } from "@wordpress/i18n";
import {
  AlertTriangle,
  ArrowLeft,
  ArrowRight,
  Check,
  Info,
} from "lucide-react";
import Modal from "@libs/modal";
import useWizardState from "./useWizardState";
import WizardReviewStep from "./WizardReviewStep";
import WizardStepRenderer from "./WizardStepRenderer";
import { WIZARD_STEPS } from "./wizardQuestions";

const ProgressIndicator = ({ currentStep }) => {
  return (
    <div className="arraysubs-setup-wizard__progress">
      {WIZARD_STEPS.map((step, index) => {
        const isActive = index === currentStep;
        const isDone = index < currentStep;

        return (
          <div className="arraysubs-setup-wizard__progress-item" key={step.id}>
            <div
              className={`arraysubs-setup-wizard__progress-step ${
                isActive ? "arraysubs-setup-wizard__progress-step--active" : ""
              } ${isDone ? "arraysubs-setup-wizard__progress-step--done" : ""}`}
            >
              {isDone ? <Check size={14} /> : index + 1}
            </div>
            <span className="arraysubs-setup-wizard__progress-label">
              {step.title}
            </span>
            {index < WIZARD_STEPS.length - 1 && (
              <span
                className={`arraysubs-setup-wizard__progress-line ${
                  isDone ? "arraysubs-setup-wizard__progress-line--done" : ""
                }`}
              />
            )}
          </div>
        );
      })}
    </div>
  );
};

const SetupWizard = ({ isOpen, onClose, onComplete }) => {
  const isProActive = useMemo(() => {
    const classes = window.arraySubs?.liveBootClasses || [];
    return classes.some((cls) => cls.includes("ArraySubsPro"));
  }, []);
  const wizardContainerRef = useRef(null);
  const [showCloseConfirm, setShowCloseConfirm] = useState(false);
  const wizard = useWizardState({ isProActive });
  const { resetWizard } = wizard;

  useEffect(() => {
    if (isOpen) {
      resetWizard();
      setShowCloseConfirm(false);
      return;
    }

    setShowCloseConfirm(false);
  }, [isOpen, resetWizard]);

  useLayoutEffect(() => {
    if (!isOpen) {
      return;
    }

    const scrollContainer = wizardContainerRef.current?.closest(
      ".arraysubs-modal__content",
    );

    if (!scrollContainer) {
      return;
    }

    scrollContainer.scrollTop = 0;
  }, [isOpen, wizard.currentStep]);

  const handleAttemptClose = () => {
    if (wizard.isSubmitting) {
      return;
    }

    setShowCloseConfirm(true);
  };

  const handleConfirmClose = () => {
    setShowCloseConfirm(false);
    resetWizard();
    onClose?.();
  };

  const handleCancelClose = () => {
    setShowCloseConfirm(false);
  };

  const handlePrimaryAction = async () => {
    if (!wizard.isReviewStep) {
      wizard.goNext();
      return;
    }

    const result = await wizard.submitWizard();
    if (!result) {
      return;
    }

    resetWizard();
    onComplete?.(result);
  };

  return (
    <Modal
      isOpen={isOpen}
      onClose={handleAttemptClose}
      size="lg"
      title={__("Setup Wizard", "arraysubs")}
      closeOnBackdrop={false}
      closeOnEsc={false}
      className="arraysubs-setup-wizard-modal"
    >
      <div className="arraysubs-setup-wizard" ref={wizardContainerRef}>
        {!isProActive && (
          <div className="arraysubs-setup-wizard__inline-note">
            <Info size={16} />
            <span>
              {__(
                "ArraySubs Pro is not active, so Pro-only wizard options are hidden for now.",
                "arraysubs",
              )}
            </span>
          </div>
        )}

        <ProgressIndicator currentStep={wizard.currentStep} />

        {wizard.isReviewStep ? (
          <WizardReviewStep
            answers={wizard.answers}
            goToStep={wizard.goToStep}
            isProActive={isProActive}
          />
        ) : (
          <WizardStepRenderer
            step={wizard.stepMeta}
            questions={wizard.visibleQuestions}
            answers={wizard.answers}
            onAnswerChange={wizard.setAnswer}
            validationErrors={wizard.validationErrors}
            isProActive={isProActive}
          />
        )}

        {wizard.submitError && (
          <div className="arraysubs-setup-wizard__submit-error">
            <AlertTriangle size={16} />
            <span>{wizard.submitError}</span>
          </div>
        )}

        <div className="arraysubs-setup-wizard__footer">
          <button
            type="button"
            className="button button-secondary arraysubs-setup-wizard__footer-back"
            onClick={wizard.goBack}
            disabled={!wizard.canGoBack || wizard.isSubmitting}
          >
            <span>{__("Back", "arraysubs")}</span>
          </button>

          <div className="arraysubs-setup-wizard__footer-actions">
            {!wizard.isReviewStep && (
              <button
                type="button"
                className="button button-link arraysubs-setup-wizard__footer-skip"
                onClick={wizard.skipCurrentStep}
                disabled={wizard.isSubmitting}
              >
                {__("Skip with defaults", "arraysubs")}
              </button>
            )}

            <button
              type="button"
              className="button button-primary arraysubs-setup-wizard__footer-next"
              onClick={handlePrimaryAction}
              disabled={wizard.isSubmitting}
            >
              {wizard.isSubmitting ? (
                <>
                  <span className="spinner is-active" />
                  <span>{__("Applying…", "arraysubs")}</span>
                </>
              ) : wizard.isReviewStep ? (
                <span>{__("Apply Settings", "arraysubs")}</span>
              ) : (
                <>
                  <span>{__("Next", "arraysubs")}</span>
                </>
              )}
            </button>
          </div>
        </div>

        {showCloseConfirm && (
          <div className="arraysubs-setup-wizard__cancel-confirm">
            <div className="arraysubs-setup-wizard__cancel-confirm-card">
              <div className="arraysubs-setup-wizard__cancel-confirm-header">
                <AlertTriangle size={20} />
                <strong>{__("Discard wizard progress?", "arraysubs")}</strong>
              </div>
              <p>
                {__(
                  "Closing the wizard will discard the answers from this session. Your current plugin settings will stay unchanged.",
                  "arraysubs",
                )}
              </p>
              <div className="arraysubs-setup-wizard__cancel-confirm-actions">
                <button
                  type="button"
                  className="button button-link"
                  onClick={handleCancelClose}
                >
                  {__("Keep working", "arraysubs")}
                </button>
                <button
                  type="button"
                  className="button button-secondary"
                  onClick={handleConfirmClose}
                >
                  {__("Discard wizard", "arraysubs")}
                </button>
              </div>
            </div>
          </div>
        )}
      </div>
    </Modal>
  );
};

export default SetupWizard;
