/** An old audience changes only after an author reviews and applies conversion. */
import { useState } from "@wordpress/element";
import { Button, Notice } from "@wordpress/components";
import { __ } from "@wordpress/i18n";
import AccessRuleSections, { AccessSection } from "./AccessRuleSections";
import legacyAccessSummary from "./legacyAccessSummary";
import { currentAccessDraft, legacyAccessDescriptor } from "./restrictionCompatibility";

export default function LegacyAccessNotice({
  config,
  update,
  statusOptions = [],
  roleOptions = [],
  Section = AccessSection,
}) {
  const [draft, setDraft] = useState(null);
  const legacy = legacyAccessDescriptor(config);
  const isTree = legacy.mode === "conditions";
  const changesGuests = legacy.mode === "visibility" && legacy.show === "logged_out" && !legacy.loginOnly;

  return (
    <Section title={__("Previous access rules", "arraysubs")} initialOpen={true}>
      <Notice status="info" isDismissible={false}>
        {__("These settings keep their original access behavior. Saving this content or editing its message does not convert the access rules.", "arraysubs")}
      </Notice>
      <p>{legacyAccessSummary(config)}</p>
      {legacy.fallback && (
        <details className="arraysubs-legacy-access__details">
          <summary>{__("Saved fallback content", "arraysubs")}</summary>
          <pre>{legacy.fallback}</pre>
        </details>
      )}
      {legacy.shortcodeAttributes && !isTree && (
        <details className="arraysubs-legacy-access__details">
          <summary>{__("Saved access conditions", "arraysubs")}</summary>
          <pre>{JSON.stringify(legacy.shortcodeAttributes, null, 2)}</pre>
        </details>
      )}
      {isTree && (
        <details className="arraysubs-legacy-access__details">
          <summary>{__("Saved condition tree", "arraysubs")}</summary>
          <pre>{JSON.stringify(legacy.conditions, null, 2)}</pre>
        </details>
      )}
      {!draft ? (
        <Button
          __next40pxDefaultSize
          variant="secondary"
          onClick={() => setDraft(currentAccessDraft(config))}
        >
          {__("Review current access rules", "arraysubs")}
        </Button>
      ) : (
        <div className="arraysubs-legacy-access__review">
          <Notice status="warning" isDismissible={false}>
            {isTree
              ? __("The saved condition tree cannot be copied into these fields. Rebuild the access rules below. The original tree stays active until you choose Use current access rules and save the content.", "arraysubs")
              : changesGuests
                ? __("The current rules do not offer guests-only access. This draft starts with logged-in users. Review the audience below before replacing the previous visibility rule.", "arraysubs")
                : legacy.loginOnly || legacy.mode === "visibility"
                  ? __("This draft starts with logged-in users only. Previously ignored conditions are not applied. Review the fields below before replacing the previous access rules.", "arraysubs")
                  : __("The current rules require login before checking any conditions. Review the audience below before replacing the previous access rules.", "arraysubs")}
          </Notice>
          <AccessRuleSections
            config={draft}
            update={(patch) => setDraft((previous) => ({ ...previous, ...patch }))}
            statusOptions={statusOptions}
            roleOptions={roleOptions}
            includeAdmin={false}
          />
          {legacy.mode === "visibility" && legacy.fallback && (
            <p>{__("The saved fallback will become the custom denial message after conversion.", "arraysubs")}</p>
          )}
          <div className="arraysubs-legacy-access__actions">
            <Button __next40pxDefaultSize variant="primary" onClick={() => update({
              ...draft,
              enabled: config.enabled,
              showToAdmins: config.showToAdmins,
              deniedAction: config.deniedAction,
              redirectType: config.redirectType,
              redirectPageId: config.redirectPageId,
              redirectPageLabel: config.redirectPageLabel,
              redirectUrl: config.redirectUrl,
              ...(legacy.mode !== "visibility" || !legacy.fallback
                ? { message: config.message, useDefaultMessage: config.useDefaultMessage }
                : {}),
            })}>
              {__("Use current access rules", "arraysubs")}
            </Button>
            <Button __next40pxDefaultSize variant="tertiary" onClick={() => setDraft(null)}>
              {__("Keep previous access rules", "arraysubs")}
            </Button>
          </div>
        </div>
      )}
    </Section>
  );
}
