import { useEffect, useRef, useState } from "react";
import { __ } from "@wordpress/i18n";
import { BadgeCheck, KeyRound, LockKeyhole, Sparkles } from "lucide-react";
import DefaultPageLayout from "@/components/DefaultPageLayout";
import { useConfirm } from "@libs/confirm-dialog";
import SpinnerButton from "@libs/confirm-dialog/SpinnerButton";
import { ToastContainer, useToast } from "@libs/toast";

const getApiConfig = () => {
  const env = window.arraySubs?.env || {};

  return {
    apiBaseUrl: `${env?.apiBaseUrl || ""}arraysubs/v1`,
    nonce: env?.nonce || "",
  };
};

const parseResponse = async (response) => {
  const result = await response.json().catch(() => ({}));

  if (!response.ok) {
    throw new Error(
      result?.message ||
        result?.error ||
        __("License request failed.", "arraysubs"),
    );
  }

  return result;
};

const maskLicenseKey = (license) => {
  const key = String(license?.licenseKey || "").trim();

  if (!key) {
    return "****-****-****";
  }

  const visibleTail = key.slice(-4);

  return `****-****-****-${visibleTail}`;
};

const License = () => {
  const [licenseKey, setLicenseKey] = useState("");
  const [license, setLicense] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isActivating, setIsActivating] = useState(false);
  const [isRemoving, setIsRemoving] = useState(false);
  const reloadToastIdRef = useRef(null);
  const { toasts, showToast, removeToast } = useToast();
  const { confirm, confirmDialog } = useConfirm();

  useEffect(() => {
    let isMounted = true;
    const { apiBaseUrl, nonce } = getApiConfig();

    const loadLicense = async () => {
      try {
        const response = await fetch(`${apiBaseUrl}/license`, {
          headers: {
            "X-WP-Nonce": nonce,
          },
        });
        const result = await parseResponse(response);

        if (!isMounted) {
          return;
        }

        setLicense(result?.content?.active ? result.content.license : null);
      } catch (error) {
        if (isMounted) {
          showToast(error.message, "error");
        }
      } finally {
        if (isMounted) {
          setIsLoading(false);
        }
      }
    };

    loadLicense();

    return () => {
      isMounted = false;
    };
  }, [showToast]);

  const handleSubmit = async (event) => {
    event.preventDefault();

    const key = licenseKey.trim();

    // Freemius license keys are case-sensitive and may contain symbols.
    if (!/^\S{10,128}$/.test(key)) {
      showToast(
        __(
          "Enter the license key from the license page in your ArrayHash portal.",
          "arraysubs",
        ),
        "error",
      );
      return;
    }

    setIsActivating(true);

    try {
      const { apiBaseUrl, nonce } = getApiConfig();
      const response = await fetch(`${apiBaseUrl}/license/activate`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "X-WP-Nonce": nonce,
        },
        body: JSON.stringify({
          license_key: key,
        }),
      });
      const result = await parseResponse(response);

      setLicense(result?.content?.license || null);
      setLicenseKey("");
      reloadToastIdRef.current = showToast(
        result?.message || __("License activated successfully.", "arraysubs"),
        "success",
      );
    } catch (error) {
      showToast(error.message, "error");
    } finally {
      setIsActivating(false);
    }
  };

  const handleRemoveLicense = async () => {
    try {
      await confirm({
        title: __("Remove License", "arraysubs"),
        message: __(
          "This will remove the license from this WordPress site only. Your seat in the ArrayHash portal stays assigned to this domain, and you can re-activate here any time. Continue?",
          "arraysubs",
        ),
        confirmText: __("Remove License", "arraysubs"),
        cancelText: __("Keep License", "arraysubs"),
        loadingText: __("Removing...", "arraysubs"),
        variant: "warning",
        onConfirm: async () => {
          setIsRemoving(true);

          try {
            const { apiBaseUrl, nonce } = getApiConfig();
            const response = await fetch(`${apiBaseUrl}/license`, {
              method: "DELETE",
              headers: {
                "X-WP-Nonce": nonce,
              },
            });
            const result = await parseResponse(response);

            setLicense(null);
            reloadToastIdRef.current = showToast(
              result?.message ||
                __("License removed from this WordPress site.", "arraysubs"),
              "success",
            );
          } finally {
            setIsRemoving(false);
          }
        },
      });
    } catch (error) {
      setIsRemoving(false);
      showToast(error.message, "error");
    }
  };

  const handleToastClose = (toastId) => {
    removeToast(toastId);

    if (reloadToastIdRef.current === toastId) {
      reloadToastIdRef.current = null;
      window.location.reload();
    }
  };

  return (
    <DefaultPageLayout title={__("License", "arraysubs")}>
      <section
        className="arraysubs-license"
        aria-label={__("ArraySubs Pro license", "arraysubs")}
      >
        {isLoading ? (
          <div className="arraysubs-license__panel arraysubs-license__panel--loading">
            <span className="spinner is-active" />
          </div>
        ) : license ? (
          <div className="arraysubs-license__panel arraysubs-license__panel--active">
            <div className="arraysubs-license__active-mark" aria-hidden="true">
              <BadgeCheck />
            </div>
            <div className="arraysubs-license__active-copy">
              <h2 className="arraysubs-license__title">
                {__("License is activated.", "arraysubs")}
              </h2>
              <div className="arraysubs-license__masked-key">
                <LockKeyhole aria-hidden="true" />
                <code>{maskLicenseKey(license)}</code>
              </div>
            </div>
            <div className="arraysubs-license__actions">
              <SpinnerButton
                type="button"
                className="button button-secondary arraysubs-license__remove"
                loading={isRemoving}
                loadingText={__("Removing...", "arraysubs")}
                onClick={handleRemoveLicense}
              >
                {__("Remove License", "arraysubs")}
              </SpinnerButton>
            </div>
          </div>
        ) : (
          <div className="arraysubs-license__grid">
            <form className="arraysubs-license__panel" onSubmit={handleSubmit}>
              <div className="arraysubs-license__intro">
                <span className="arraysubs-license__eyebrow">
                  <Sparkles aria-hidden="true" />
                  {__("Premium Access", "arraysubs")}
                </span>
                <h2 className="arraysubs-license__title">
                  {__("Activate ArraySubs Pro", "arraysubs")}
                </h2>
                <p className="arraysubs-license__description">
                  {__(
                    "Connect this site to your ArrayHash license to unlock premium updates and services.",
                    "arraysubs",
                  )}
                </p>
              </div>

              <label
                className="arraysubs-license__label"
                htmlFor="arraysubs-license-key"
              >
                {__("License key", "arraysubs")}
              </label>
              <div className="arraysubs-license__field-row">
                <div className="arraysubs-license__input-wrap">
                  <KeyRound
                    aria-hidden="true"
                    className="arraysubs-license__input-icon"
                  />
                  <input
                    id="arraysubs-license-key"
                    className="regular-text arraysubs-license__input"
                    type="text"
                    value={licenseKey}
                    onChange={(event) => setLicenseKey(event.target.value)}
                    autoComplete="off"
                    spellCheck={false}
                    maxLength={128}
                    required
                  />
                </div>
                <SpinnerButton
                  type="submit"
                  className="button button-primary arraysubs-license__activate"
                  loading={isActivating}
                  loadingText={__("Activating...", "arraysubs")}
                >
                  {__("Activate License", "arraysubs")}
                </SpinnerButton>
              </div>
            </form>

            <aside className="arraysubs-license__guide">
              <h3>{__("How to get your license", "arraysubs")}</h3>
              <p>
                {__(
                  "Instructions will be added here soon.",
                  "arraysubs",
                )}
              </p>
            </aside>
          </div>
        )}
      </section>

      {confirmDialog}
      <ToastContainer toasts={toasts} removeToast={handleToastClose} />
    </DefaultPageLayout>
  );
};

export default License;
