import React, { useEffect, useRef, useState } from "react";
import { createRoot } from "react-dom/client";
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;

// 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]");
      const plugin = config.plugins.find((item) => item.file === row?.dataset.plugin);
      if (!plugin) 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({ ...plugin, 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", request.slug);
    data.set("offboarding_nonce", request.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(config.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={request ? sprintf(
          /* translators: %s: plugin name. */
          __("Before you deactivate %s", "arraysubs"), request.name,
        ) : ""}
        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) => setReasons((current) => event.target.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__disclosure">
            {__("Either action shares your reasons, saved notification email (if available), website URL and plugin details with ArrayHash. Get Help Directly opens our contact page in a new tab and keeps the plugin active.", "arraysubs")}
          </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 (config?.plugins?.length) {
  const host = document.createElement("div");
  host.id = "arraysubs-offboarding-host";
  document.body.appendChild(host);
  createRoot(host).render(<Offboarding />);
}
