import React from "react";
import { __ } from "@wordpress/i18n";
import { getFields, STEP_LABELS, subscriptionModes } from "./fields";

const displayValue = (field, value) => {
  if (typeof value === "boolean") return value ? __("Yes", "arraysubs") : __("No", "arraysubs");
  const labels = (field.name === "_arraysubs_subscription_mode" ? subscriptionModes : null) || (Array.isArray(field.data) ? Object.fromEntries(field.data.map(({value, label}) => [value, label])) : field.data || {});
  if (Array.isArray(value)) return value.map((v) => labels[v] || v).join(", ");
  return labels[value] || (value === "" || value == null ? __("Not set", "arraysubs") : String(value));
};

export default function ProductReview({ values, options, type, steps, sync, goToStep }) {
  return <div className="arraysubs-quick-product__review">
    <p>{__("Check these details before publishing your product to the shop.", "arraysubs")}</p>
    {steps.filter((step) => !["type", "review"].includes(step)).map((step) => {
      const fields = getFields(step, values, options, type);
      if (step === "sync") return <section key={step}>
        <h3>{STEP_LABELS[step]} <button type="button" className="button-link" onClick={() => goToStep(step)}>{__("Edit", "arraysubs")}</button></h3>
        <p>{values._subscription_period === "lifetime" ? __("Lifetime products do not renew.", "arraysubs") : sync.enabled ? __("Custom renewal segment plan enabled.", "arraysubs") : __("Use store-wide renewal settings.", "arraysubs")}</p>
        {sync.enabled && <dl>{[
          [__("First boundary (day)", "arraysubs"), sync.seg1_end],
          [__("Second boundary (day)", "arraysubs"), sync.seg2_end],
          [__("Full amount segment", "arraysubs"), sync.seg1_active],
          [__("Prorated amount segment", "arraysubs"), sync.seg2_active],
          [__("Next billing cycle segment", "arraysubs"), sync.seg3_active],
        ].map(([label, value]) => <React.Fragment key={label}><dt>{label}</dt><dd>{displayValue({}, value)}</dd></React.Fragment>)}</dl>}
      </section>;
      if (!fields.length) return null;
      return <section key={step}>
        <h3>{STEP_LABELS[step]} <button type="button" className="button-link" onClick={() => goToStep(step)}>{__("Edit", "arraysubs")}</button></h3>
        <dl>{fields.map((f) => <React.Fragment key={f.name}><dt>{f.label}</dt><dd>{displayValue(f, values[f.name])}</dd></React.Fragment>)}</dl>
      </section>;
    })}
  </div>;
}
