import React, { useEffect, useRef, useState } from "react";
import { createRoot } from "react-dom/client";
import { createInterpolateElement } from "@wordpress/element";
import { __, sprintf } from "@wordpress/i18n";
import Modal from "@libs/modal";
import SpinnerButton from "@libs/confirm-dialog/SpinnerButton";
import { ToastContainer, useToast } from "@libs/toast";
import "@libs/toast/toast.scss";
import "./scss/offboarding.scss";

const config = window.arraySubsOffboarding;
const plugin = config?.plugin;

const supportMessages = {
  default: __(
    /* translators: Keep the <strong> tags around the emphasized words. */
    "What would you like to build with ArraySubs? We'd be happy to <strong>walk you through setup</strong> or record a <strong>personalized video</strong> for your site.",
    "arraysubs",
  ),
  missing_feature: __(
    /* translators: Keep the <strong> tags around the emphasized words. */
    "Tell us about the <strong>feature you're looking for</strong> and what you need it to do. We'll check what's possible in ArraySubs and help you find a way forward.",
    "arraysubs",
  ),
  not_working: __(
    /* translators: Keep the <strong> tags around the emphasized words. */
    "Tell us <strong>what broke and where you saw it</strong>. We'd be happy to look into it with you and help you get things working.",
    "arraysubs",
  ),
  found_alternative: __(
    /* translators: Keep the <strong> tags around the emphasized words. */
    "What made the other option a better fit? Tell us about the <strong>workflow that matters to you</strong> and we'll see how ArraySubs could help.",
    "arraysubs",
  ),
  cannot_find_settings: __(
    /* translators: Keep the <strong> tags around the emphasized words. */
    "Tell us <strong>what you're trying to set up</strong>. We can point you to the right settings and walk you through them <strong>step by step</strong>.",
    "arraysubs",
  ),
  needs_improvement: __(
    /* translators: Keep the <strong> tags around the emphasized words. */
    "Tell us <strong>what slowed you down</strong> and how you expected it to work. Your feedback helps us improve, and we can help you with the task you were trying to finish.",
    "arraysubs",
  ),
  getting_started: __(
    /* translators: Keep the <strong> tags around the emphasized words. */
    "What would you like to do with <strong>subscriptions, memberships, or recurring payments</strong>? We can guide you step by step, record a video for your site, or <strong>help you set it up</strong>.",
    "arraysubs",
  ),
  other: __(
    /* translators: Keep the <strong> tags around the emphasized words. */
    "We'd like to hear <strong>what got in your way</strong>. Share as much as you'd like and let us know how we can help.",
    "arraysubs",
  ),
};

// Generate a fresh receipt per dialog, retaining it for retries within that dialog.
const eventId = () => {
  const bytes = window.crypto.getRandomValues(new Uint8Array(16));
  bytes[6] = (bytes[6] & 15) | 64;
  bytes[8] = (bytes[8] & 63) | 128;
  const hex = Array.from(bytes, (value) => value.toString(16).padStart(2, "0")).join("");
  return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
};

const Offboarding = () => {
  const [request, setRequest] = useState(null);
  const [reasons, setReasons] = useState([]);
  const [other, setOther] = useState("");
  const [busy, setBusy] = useState("");
  const submitting = useRef(false);
  const { toasts, showToast, removeToast } = useToast();

  useEffect(() => {
    const open = (event) => {
      const link = event.target.closest("a");
      if (!link || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
      const row = link.closest("tr[data-plugin]");
      if (row?.dataset.plugin !== plugin.file) return;
      const url = new URL(link.href, window.location.href);
      if (url.origin !== window.location.origin || url.searchParams.get("action") !== "deactivate"
        || url.searchParams.get("plugin") !== plugin.file) return;
      event.preventDefault();
      if (submitting.current) return;
      setReasons([]);
      setOther("");
      setRequest({ eventId: eventId(), url: link.href });
    };
    document.addEventListener("click", open);
    return () => document.removeEventListener("click", open);
  }, []);

  const close = () => {
    if (!submitting.current) setRequest(null);
  };

  const fields = () => {
    const data = new FormData();
    data.set("plugin_slug", plugin.slug);
    data.set("offboarding_nonce", plugin.nonce);
    data.set("event_id", request.eventId);
    reasons.forEach((reason) => data.append("reasons[]", reason));
    data.set("other_reason", reasons.includes("other") ? other : "");
    return data;
  };

  const deactivate = () => {
    if (submitting.current) return;
    submitting.current = true;
    setBusy("deactivate");
    // Send feedback with WordPress's actual, nonce-protected deactivation. The
    // server hook creates the receipt within WordPress's deactivation flow.
    const form = document.createElement("form");
    form.method = "post";
    form.action = request.url;
    form.hidden = true;
    for (const [name, value] of fields()) {
      const input = document.createElement("input");
      input.type = "hidden";
      input.name = name;
      input.value = value;
      form.appendChild(input);
    }
    document.body.appendChild(form);
    form.submit();
  };

  const getHelp = async () => {
    if (submitting.current) return;
    submitting.current = true;
    setBusy("help");
    // Open synchronously in the click gesture; the portal request never gates
    // access to the contact page or deactivates the plugin.
    window.open(plugin.contactUrl, "_blank", "noopener,noreferrer");
    const data = fields();
    data.set("action", "arraysubs_offboarding_help");
    const controller = new AbortController();
    const timeout = window.setTimeout(() => controller.abort(), 15000);
    try {
      const response = await fetch(config.ajaxUrl, {
        method: "POST",
        credentials: "same-origin",
        body: data,
        signal: controller.signal,
      });
      const result = await response.json();
      if (!response.ok || !result.success) {
        throw new Error(result?.data?.message || __("Could not save your feedback. You can still contact us in the new tab.", "arraysubs"));
      }
      showToast(result.data.delivered
        ? __("Feedback sent. Your plugin stays active while you contact us.", "arraysubs")
        : __("Feedback saved for retry. Your plugin stays active while you contact us.", "arraysubs"),
      result.data.delivered ? "success" : "info");
      setRequest(null);
    } catch (error) {
      showToast(error.name === "AbortError"
        ? __("Feedback delivery is taking longer than expected. Your plugin stays active; you can contact us in the new tab.", "arraysubs")
        : error.message, "error");
    } finally {
      window.clearTimeout(timeout);
      submitting.current = false;
      setBusy("");
    }
  };

  return (
    <>
      <Modal
        isOpen={Boolean(request)}
        onClose={close}
        size="md"
        title={sprintf(
          /* translators: %s: plugin name. */
          __("Before you deactivate %s", "arraysubs"), "ArraySubs",
        )}
        className="arraysubs-offboarding-modal"
        closeOnBackdrop={!busy}
        closeOnEsc={!busy}
        showCloseButton={!busy}
      >
        <div className="arraysubs-offboarding">
          <fieldset disabled={Boolean(busy)}>
            <legend>{__("What could we improve? Select any reasons, or leave them blank.", "arraysubs")}</legend>
            {Object.entries(config.reasons).map(([key, label]) => (
              <label className="arraysubs-offboarding__reason" key={key}>
                <input
                  type="checkbox"
                  checked={reasons.includes(key)}
                  onChange={(event) => {
                    const { checked } = event.target;
                    setReasons((current) => checked
                      ? [...current, key] : current.filter((reason) => reason !== key));
                  }}
                />
                <span>{label}</span>
              </label>
            ))}
            {reasons.includes("other") && (
              <label className="arraysubs-offboarding__other">
                <span>{__("Tell us more (optional)", "arraysubs")}</span>
                <textarea rows={3} maxLength={4000} value={other} onChange={(event) => setOther(event.target.value)} />
              </label>
            )}
          </fieldset>
          <p className="arraysubs-offboarding__message" role="status" aria-atomic="true">
            {createInterpolateElement(
              supportMessages[reasons[reasons.length - 1]] ?? supportMessages.default,
              { strong: <strong /> },
            )}
          </p>
          <div className="arraysubs-offboarding__actions">
            <SpinnerButton
              type="button"
              className="button-link"
              disabled={Boolean(busy)}
              loading={busy === "deactivate"}
              loadingText={__("Deactivating…", "arraysubs")}
              onClick={deactivate}
            >
              {__("Deactivate now", "arraysubs")}
            </SpinnerButton>
            <SpinnerButton
              type="button"
              className="button button-primary"
              disabled={Boolean(busy)}
              loading={busy === "help"}
              loadingText={__("Sending…", "arraysubs")}
              onClick={getHelp}
            >
              {__("Get Help Directly", "arraysubs")}
            </SpinnerButton>
          </div>
        </div>
      </Modal>
      <ToastContainer toasts={toasts} removeToast={removeToast} />
    </>
  );
};

if (plugin) {
  const host = document.createElement("div");
  host.id = "arraysubs-offboarding-host";
  document.body.appendChild(host);
  createRoot(host).render(<Offboarding />);
}
