import React, { useCallback, useEffect, useState } from "react";
import { __, sprintf } from "@wordpress/i18n";
import DefaultPageLayout from "@/components/DefaultPageLayout";
import ProOnlyMessage from "@/components/ProOnlyMessage";
import { getRouteVisiblity } from "@libs/menu-visibility";
import { ToastContainer, useToast } from "@libs/toast";
import { useConfirm } from "@libs/confirm-dialog";
import SpinnerButton from "@libs/confirm-dialog/SpinnerButton";
import Modal from "@libs/modal";
import { buildRestUrl } from "@libs/url";
import { formatDateTimeForSite } from "@/libs/dateTime";
import {
  AlertTriangle,
  CheckCircle,
  ChevronLeft,
  ChevronRight,
  Eye,
  RefreshCw,
} from "lucide-react";

const formatTimestamp = (value) => {
  if (!value) {
    return "-";
  }

  return formatDateTimeForSite(value, "-");
};

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

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

  return payload;
};

const HttpStatusBadge = ({ status }) => (
  <span className="arraysubs-job-status arraysubs-job-status--failed">
    <AlertTriangle size={14} />
    <span>{status || "-"}</span>
  </span>
);

const FailureDetailsModal = ({ failure, onClose }) => {
  const context = failure?.context || {};

  return (
    <Modal
      isOpen={Boolean(failure)}
      onClose={onClose}
      title={failure?.action_label || __("Portal Action Failure", "arraysubs")}
      size="lg"
    >
      <div className="arraysubs-portal-failure-details">
        <dl>
          <dt>{__("Error", "arraysubs")}</dt>
          <dd>
            <code>{failure?.error_code || "-"}</code>
            {failure?.http_status ? ` HTTP ${failure.http_status}` : ""}
          </dd>

          <dt>{__("Message", "arraysubs")}</dt>
          <dd>{failure?.message || "-"}</dd>

          <dt>{__("Suggested Resolution", "arraysubs")}</dt>
          <dd>{failure?.suggested_resolution || "-"}</dd>

          <dt>{__("Request", "arraysubs")}</dt>
          <dd>
            <code>
              {failure?.method || "POST"} {failure?.route || "-"}
            </code>
          </dd>

          <dt>{__("Context", "arraysubs")}</dt>
          <dd>
            <pre>{JSON.stringify(context, null, 2)}</pre>
          </dd>
        </dl>
      </div>
    </Modal>
  );
};

const PortalActionFailuresContent = () => {
  const { env } = window.arraySubs;
  const { toasts, showToast, removeToast } = useToast();
  const { confirm, confirmDialog } = useConfirm();
  const [loading, setLoading] = useState(true);
  const [failures, setFailures] = useState([]);
  const [selectedFailure, setSelectedFailure] = useState(null);
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(0);
  const [totalPages, setTotalPages] = useState(0);
  const [processingId, setProcessingId] = useState(0);
  const perPage = 30;

  const fetchFailures = useCallback(
    async (currentPage = 1) => {
      setLoading(true);

      try {
        const response = await fetch(
          buildRestUrl(
            env?.apiBaseUrl,
            "arraysubs/v1/audits/portal-action-failures",
            {
              page: currentPage,
              per_page: perPage,
            },
          ),
          {
            headers: { "X-WP-Nonce": env?.nonce },
          },
        );
        const result = await normalizeResponse(
          response,
          __("Failed to load portal action failures.", "arraysubs"),
        );
        const content = result.content || {};

        setFailures(content.failures || []);
        setTotal(content.total || 0);
        setTotalPages(content.total_pages || 0);
        setPage(content.page || currentPage);
      } catch (error) {
        showToast(error.message, "error");
      } finally {
        setLoading(false);
      }
    },
    [env?.apiBaseUrl, env?.nonce],
  );

  useEffect(() => {
    fetchFailures(1);
  }, []);

  const handleResolve = async (failure) => {
    try {
      await confirm({
        title: __("Resolve Portal Failure", "arraysubs"),
        message: __(
          "Mark this portal action failure as resolved? This only dismisses the troubleshooting row and records an audit entry.",
          "arraysubs",
        ),
        confirmText: __("Resolve", "arraysubs"),
        cancelText: __("Cancel", "arraysubs"),
        loadingText: __("Resolving...", "arraysubs"),
        variant: "warning",
        onConfirm: async () => {
          setProcessingId(failure.id);

          try {
            const response = await fetch(
              buildRestUrl(
                env?.apiBaseUrl,
                `arraysubs/v1/audits/portal-action-failures/${failure.id}/resolve`,
              ),
              {
                method: "POST",
                headers: { "X-WP-Nonce": env?.nonce },
              },
            );
            const result = await normalizeResponse(
              response,
              __("Failed to resolve portal action failure.", "arraysubs"),
            );

            showToast(
              result.message || __("Portal action failure resolved.", "arraysubs"),
              "success",
            );
            setSelectedFailure(null);
            fetchFailures(page);
          } finally {
            setProcessingId(0);
          }
        },
      });
    } catch (error) {
      showToast(error.message, "error");
      setProcessingId(0);
    }
  };

  const handlePageChange = (nextPage) => {
    if (nextPage < 1 || nextPage > totalPages) {
      return;
    }

    fetchFailures(nextPage);
  };

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

      <div className="arraysubs-audit-table-wrap">
        {loading && failures.length === 0 ? (
          <p className="arraysubs-loading">
            {__("Loading portal action failures...", "arraysubs")}
          </p>
        ) : failures.length === 0 ? (
          <p className="arraysubs-audit-empty">
            {__(
              "No unresolved portal action failures found. Failed customer portal REST actions appear here until resolved.",
              "arraysubs",
            )}
          </p>
        ) : (
          <table className="wp-list-table widefat fixed striped arraysubs-audit-table arraysubs-portal-failures-table">
            <thead>
              <tr>
                <th>{__("Action", "arraysubs")}</th>
                <th>{__("Customer", "arraysubs")}</th>
                <th>{__("Subscription", "arraysubs")}</th>
                <th>{__("Error Code", "arraysubs")}</th>
                <th>{__("HTTP", "arraysubs")}</th>
                <th>{__("Timestamp", "arraysubs")}</th>
                <th>{__("Actions", "arraysubs")}</th>
              </tr>
            </thead>
            <tbody>
              {failures.map((failure) => (
                <tr key={failure.id}>
                  <td>
                    <strong>{failure.action_label || failure.action}</strong>
                    <span className="arraysubs-renewal-failures-table__meta">
                      {failure.method} {failure.route}
                    </span>
                  </td>
                  <td>
                    <strong>{failure.customer_name}</strong>
                    <span className="arraysubs-renewal-failures-table__meta">
                      {failure.customer_email || "-"}
                    </span>
                  </td>
                  <td>
                    {failure.subscription_id > 0 ? (
                      <>
                        <a
                          href={failure.subscription_url}
                          className="arraysubs-audit-sub-link"
                        >
                          #{failure.subscription_id}
                        </a>
                        <span className="arraysubs-renewal-failures-table__meta">
                          {failure.subscription_label ||
                            failure.subscription_status ||
                            "-"}
                        </span>
                      </>
                    ) : (
                      "-"
                    )}
                  </td>
                  <td>
                    <code>{failure.error_code || "-"}</code>
                    <span className="arraysubs-renewal-failures-table__reason">
                      {failure.message || "-"}
                    </span>
                  </td>
                  <td>
                    <HttpStatusBadge status={failure.http_status} />
                  </td>
                  <td>{formatTimestamp(failure.created_at_timestamp)}</td>
                  <td>
                    <div className="arraysubs-renewal-failures-table__actions">
                      <button
                        type="button"
                        className="button button-small"
                        onClick={() => setSelectedFailure(failure)}
                      >
                        <Eye size={14} />
                        {__("View", "arraysubs")}
                      </button>
                      <SpinnerButton
                        type="button"
                        className="button button-small"
                        loading={processingId === failure.id}
                        loadingText={__("Resolving...", "arraysubs")}
                        onClick={() => handleResolve(failure)}
                      >
                        <CheckCircle size={14} />
                        {__("Resolve", "arraysubs")}
                      </SpinnerButton>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>

      {totalPages > 1 && (
        <div className="arraysubs-audit-pagination">
          <button
            type="button"
            className="button button-small"
            disabled={page <= 1}
            onClick={() => handlePageChange(page - 1)}
          >
            <ChevronLeft size={16} />
            {__("Previous", "arraysubs")}
          </button>
          <span className="arraysubs-audit-pagination__info">
            {__("Page", "arraysubs")} {page} {__("of", "arraysubs")}{" "}
            {totalPages}
            <span className="arraysubs-audit-pagination__total">
              ({total} {__("total", "arraysubs")})
            </span>
          </span>
          <button
            type="button"
            className="button button-small"
            disabled={page >= totalPages}
            onClick={() => handlePageChange(page + 1)}
          >
            {__("Next", "arraysubs")}
            <ChevronRight size={16} />
          </button>
        </div>
      )}

      <FailureDetailsModal
        failure={selectedFailure}
        onClose={() => setSelectedFailure(null)}
      />
      {confirmDialog}
      <ToastContainer toasts={toasts} removeToast={removeToast} />
    </>
  );
};

const PortalActionFailures = () => {
  const menuItems = window.arraySubs?.menu?.items || [];
  const visibility = getRouteVisiblity(
    "/audits/portal-action-failures",
    menuItems,
  );
  const isProActive = visibility === 1;

  return (
    <DefaultPageLayout
      title={__("Portal Action Failures", "arraysubs")}
      subtitle={
        isProActive
          ? __(
              "Troubleshooting queue for failed customer portal actions.",
              "arraysubs",
            )
          : ""
      }
    >
      {isProActive ? <PortalActionFailuresContent /> : <ProOnlyMessage />}
    </DefaultPageLayout>
  );
};

export default PortalActionFailures;
