import React, { useCallback, useEffect, useState } from "react";
import { __, sprintf } from "@wordpress/i18n";
import DefaultPageLayout from "@/components/DefaultPageLayout";
import { ToastContainer, useToast } from "@libs/toast";
import { useConfirm } from "@libs/confirm-dialog";
import SpinnerButton from "@libs/confirm-dialog/SpinnerButton";
import { buildRestUrl } from "@libs/url";
import {
  AlertTriangle,
  CheckCircle,
  ExternalLink,
  RefreshCw,
  Shield,
} from "lucide-react";

const normalizeResponse = async (response, fallbackMessage) => {
  const payload = await response.json().catch(() => ({}));

  if (!response.ok) {
    throw new Error(payload.message || fallbackMessage);
  }

  return payload;
};

const RulePanel = ({ title, rule, winner = false }) => (
  <div
    className={`arraysubs-conflict-rule${
      winner ? " arraysubs-conflict-rule--winner" : ""
    }`}
  >
    <div className="arraysubs-conflict-rule__header">
      <strong>{title}</strong>
      {winner && (
        <span className="arraysubs-conflict-rule__winner">
          <CheckCircle size={14} />
          {__("Winner", "arraysubs")}
        </span>
      )}
    </div>
    <dl>
      <dt>{__("Rule", "arraysubs")}</dt>
      <dd>{rule.name}</dd>

      <dt>{__("Type", "arraysubs")}</dt>
      <dd>{rule.type}</dd>

      {"pattern" in rule && (
        <>
          <dt>{__("Pattern", "arraysubs")}</dt>
          <dd>
            <code>{rule.pattern_type}: {rule.pattern}</code>
          </dd>
        </>
      )}

      <dt>{__("Specificity", "arraysubs")}</dt>
      <dd>{rule.specificity_score}</dd>

      <dt>{__("Effect", "arraysubs")}</dt>
      <dd>{rule.effect}</dd>

      <dt>{__("Conditions", "arraysubs")}</dt>
      <dd>{rule.conditions_label}</dd>
    </dl>
  </div>
);

const AccessRuleConflictsContent = () => {
  const { env } = window.arraySubs;
  const { toasts, showToast, removeToast } = useToast();
  const { confirm, confirmDialog } = useConfirm();
  const [loading, setLoading] = useState(true);
  const [conflicts, setConflicts] = useState([]);
  const [priorityOrder, setPriorityOrder] = useState([]);
  const [processingId, setProcessingId] = useState("");

  const fetchConflicts = useCallback(async () => {
    setLoading(true);

    try {
      const response = await fetch(
        buildRestUrl(env?.apiBaseUrl, "arraysubs/v1/members-access/conflicts"),
        {
          headers: { "X-WP-Nonce": env?.nonce },
        },
      );
      const result = await normalizeResponse(
        response,
        __("Failed to load access-rule conflicts.", "arraysubs"),
      );
      const content = result.content || {};

      setConflicts(content.conflicts || []);
      setPriorityOrder(content.priority_order || []);
    } catch (error) {
      showToast(error.message, "error");
    } finally {
      setLoading(false);
    }
  }, [env?.apiBaseUrl, env?.nonce]);

  useEffect(() => {
    fetchConflicts();
  }, []);

  const handleDisableUrlRule = async (conflict) => {
    try {
      await confirm({
        title: __("Disable URL Rule", "arraysubs"),
        message: sprintf(
          /* translators: 1: URL rule name, 2: target URL. */
          __(
            "Disable the URL rule \"%1$s\" for %2$s? This resolves the conflict and records an audit entry.",
            "arraysubs",
          ),
          conflict.url_rule.name,
          conflict.target.url,
        ),
        confirmText: __("Disable Rule", "arraysubs"),
        cancelText: __("Cancel", "arraysubs"),
        loadingText: __("Disabling...", "arraysubs"),
        variant: "warning",
        onConfirm: async () => {
          setProcessingId(conflict.id);

          try {
            const response = await fetch(
              buildRestUrl(
                env?.apiBaseUrl,
                `arraysubs/v1/members-access/conflicts/${conflict.id}/disable-url-rule`,
              ),
              {
                method: "POST",
                headers: { "X-WP-Nonce": env?.nonce },
              },
            );
            const result = await normalizeResponse(
              response,
              __("Failed to disable the URL rule.", "arraysubs"),
            );

            showToast(
              result.message || __("URL rule disabled.", "arraysubs"),
              "success",
            );
            fetchConflicts();
          } finally {
            setProcessingId("");
          }
        },
      });
    } catch (error) {
      showToast(error.message, "error");
      setProcessingId("");
    }
  };

  return (
    <>
      <div className="arraysubs-audit-filters">
        <div className="arraysubs-audit-filters__row">
          <button
            type="button"
            className="button button-small"
            onClick={fetchConflicts}
            disabled={loading}
          >
            <RefreshCw size={14} className={loading ? "arraysubs-spin" : ""} />
            {__("Refresh", "arraysubs")}
          </button>
        </div>
      </div>

      {priorityOrder.length > 0 && (
        <div className="arraysubs-conflict-priority">
          {priorityOrder.map((item, index) => (
            <span key={item}>
              {index + 1}. {item}
            </span>
          ))}
        </div>
      )}

      {loading && conflicts.length === 0 ? (
        <p className="arraysubs-loading">
          {__("Loading access-rule conflicts...", "arraysubs")}
        </p>
      ) : conflicts.length === 0 ? (
        <p className="arraysubs-audit-empty">
          {__(
            "No access-rule conflicts found. URL rules that overlap per-post overrides appear here.",
            "arraysubs",
          )}
        </p>
      ) : (
        <div className="arraysubs-conflict-list">
          {conflicts.map((conflict) => (
            <section key={conflict.id} className="arraysubs-conflict">
              <div className="arraysubs-conflict__header">
                <div>
                  <h3>{conflict.target.title}</h3>
                  <div className="arraysubs-conflict__target">
                    <code>{conflict.target.url}</code>
                    {conflict.target.view_url && (
                      <a
                        href={conflict.target.view_url}
                        target="_blank"
                        rel="noreferrer"
                      >
                        <ExternalLink size={14} />
                        {__("View", "arraysubs")}
                      </a>
                    )}
                  </div>
                </div>
                <div className="arraysubs-conflict__status">
                  <AlertTriangle size={16} />
                  <span>{conflict.winner.label}</span>
                </div>
              </div>

              <div className="arraysubs-conflict__rules">
                <RulePanel title={__("URL Rule", "arraysubs")} rule={conflict.url_rule} />
                <RulePanel
                  title={__("Per-post Rule", "arraysubs")}
                  rule={conflict.post_rule}
                  winner
                />
              </div>

              <div className="arraysubs-conflict__resolution">
                <p>{conflict.winner.reason}</p>
                <strong>{conflict.winner.effect}</strong>
                <SpinnerButton
                  type="button"
                  className="button button-primary"
                  loading={processingId === conflict.id}
                  loadingText={__("Disabling...", "arraysubs")}
                  onClick={() => handleDisableUrlRule(conflict)}
                >
                  {__("Disable URL Rule", "arraysubs")}
                </SpinnerButton>
              </div>
            </section>
          ))}
        </div>
      )}

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

const AccessRuleConflicts = () => (
  <DefaultPageLayout
    title={__("Access-Rule Conflicts", "arraysubs")}
    subtitle={__(
      "Review URL rules that overlap higher-priority per-post access overrides.",
      "arraysubs",
    )}
    icon={<Shield size={24} />}
  >
    <div className="arraysubs-members-access">
      <AccessRuleConflictsContent />
    </div>
  </DefaultPageLayout>
);

export default AccessRuleConflicts;
