import React, { useMemo, useState } from "react";
import { __, sprintf } from "@wordpress/i18n";
import { ChevronDown, ChevronUp, Info, Pencil } from "lucide-react";
import {
  getQuestionOptionLabel,
  getVisibleQuestions,
  MANUAL_SETUP_NOTES,
  WIZARD_STEPS,
} from "./wizardQuestions";

const isEmptyValue = (value) => {
  if (Array.isArray(value)) {
    return value.length === 0;
  }

  return value === undefined || value === null || value === "";
};

const formatAnswerValue = (question, value, isProActive) => {
  if (Array.isArray(value)) {
    if (value.length === 0) {
      return __("None selected", "arraysubs");
    }

    return value
      .map((item) => getQuestionOptionLabel(question, item, isProActive))
      .join(", ");
  }

  if (isEmptyValue(value)) {
    return __("Not set", "arraysubs");
  }

  if (question.options?.length) {
    return getQuestionOptionLabel(question, value, isProActive);
  }

  return String(value);
};

const WizardReviewStep = ({ answers, goToStep, isProActive }) => {
  const reviewSteps = useMemo(() => WIZARD_STEPS.slice(0, -1), []);
  const [openSections, setOpenSections] = useState(() => {
    return reviewSteps.reduce((accumulator, step) => {
      accumulator[step.id] = true;
      return accumulator;
    }, {});
  });

  const sections = useMemo(() => {
    return reviewSteps.map((step, stepIndex) => {
      const visibleQuestions = getVisibleQuestions(step, answers, isProActive);

      return {
        id: step.id,
        stepIndex,
        title: step.title,
        questions: visibleQuestions,
      };
    });
  }, [answers, isProActive, reviewSteps]);

  const answeredCount = sections.reduce((count, section) => {
    return count + section.questions.length;
  }, 0);

  const toggleSection = (sectionId) => {
    setOpenSections((previous) => ({
      ...previous,
      [sectionId]: !previous[sectionId],
    }));
  };

  return (
    <div className="arraysubs-setup-wizard__review">
      <div className="arraysubs-setup-wizard__step-header">
        <h3 className="arraysubs-setup-wizard__step-title">
          {__("Review your configuration", "arraysubs")}
        </h3>
        <p className="arraysubs-setup-wizard__step-description">
          {__(
            "Take one last look before the wizard applies your subscription settings.",
            "arraysubs",
          )}
        </p>
      </div>

      <div className="arraysubs-setup-wizard__review-summary">
        <Info size={18} />
        <div>
          <strong>
            {sprintf(
              /* translators: %d: number of visible wizard answers in the review. */
              __("%d answers are ready to apply.", "arraysubs"),
              answeredCount,
            )}
          </strong>
          <p>
            {__(
              "The wizard only applies the supported settings below. Advanced rules and content structures stay untouched.",
              "arraysubs",
            )}
          </p>
        </div>
      </div>

      <div className="arraysubs-setup-wizard__review-sections">
        {sections.map((section) => {
          const isOpen = openSections[section.id] !== false;
          const Icon = isOpen ? ChevronUp : ChevronDown;

          return (
            <div
              key={section.id}
              className={`arraysubs-setup-wizard__review-section ${
                isOpen ? "arraysubs-setup-wizard__review-section--open" : ""
              }`}
            >
              <div className="arraysubs-setup-wizard__review-section-header">
                <button
                  type="button"
                  className="arraysubs-setup-wizard__review-section-toggle"
                  onClick={() => toggleSection(section.id)}
                >
                  <span>{section.title}</span>
                  <Icon size={16} />
                </button>
                <button
                  type="button"
                  className="arraysubs-setup-wizard__review-section-edit"
                  onClick={() => goToStep(section.stepIndex)}
                >
                  <Pencil size={14} />
                  <span>{__("Edit", "arraysubs")}</span>
                </button>
              </div>

              {isOpen && (
                <div className="arraysubs-setup-wizard__review-section-body">
                  {section.questions.map((question) => (
                    <div
                      key={question.key}
                      className="arraysubs-setup-wizard__review-item"
                    >
                      <span className="arraysubs-setup-wizard__review-item-label">
                        {question.label}
                      </span>
                      <span className="arraysubs-setup-wizard__review-item-value">
                        {formatAnswerValue(
                          question,
                          answers[question.key],
                          isProActive,
                        )}
                      </span>
                    </div>
                  ))}
                </div>
              )}
            </div>
          );
        })}
      </div>

      <div className="arraysubs-setup-wizard__review-note">
        <strong>
          {__("Still configure manually after the wizard:", "arraysubs")}
        </strong>
        <ul>
          {MANUAL_SETUP_NOTES.map((note) => (
            <li key={note}>{note}</li>
          ))}
        </ul>
      </div>
    </div>
  );
};

export default WizardReviewStep;
