import React, { useState, useEffect, useCallback } from "react";
import { __ } from "@wordpress/i18n";
import DefaultPageLayout from "@/components/DefaultPageLayout";
import { ToastContainer, useToast } from "@libs/toast";
import { buildUrl } from "@/libs/url";
import { formatDateTimeForSite } from "@/libs/dateTime";
import {
  Zap,
  CheckCircle,
  AlertTriangle,
  XCircle,
  ExternalLink,
  RefreshCw,
  Clock,
  Activity,
  ChevronDown,
  ChevronUp,
} from "lucide-react";

const CAPABILITY_LABELS = {
  automatic_payments: __("subscription", "arraysubs"),
  trials: __("trial", "arraysubs"),
  pause: __("pause", "arraysubs"),
  resume: __("resume", "arraysubs"),
  cancel_at_period_end: __("cancel at period end", "arraysubs"),
  cancel_at_period_end_reversible: __("reversible cancellation", "arraysubs"),
  retention_amount_update: __("retention amount update", "arraysubs"),
  product_sync: __("product sync", "arraysubs"),
  payment_method_update: __("payment method update", "arraysubs"),
  card_auto_update: __("card auto update", "arraysubs"),
  card_expiry_notice: __("card expiry notice", "arraysubs"),
  disputes: __("disputes", "arraysubs"),
  sca: __("SCA", "arraysubs"),
  refunds: __("refunds", "arraysubs"),
  hosted_payment_page: __("hosted payment page", "arraysubs"),
  customer_portal: __("customer portal", "arraysubs"),
  mixed_cart: __("mixed cart", "arraysubs"),
  multiple_subscriptions: __("multiple subscriptions", "arraysubs"),
  different_billing_cycles: __("different billing cycles", "arraysubs"),
  supports_sync: __("gateway sync", "arraysubs"),
};

const getCapabilityTags = (capabilities) => {
  if (Array.isArray(capabilities)) {
    return capabilities
      .filter(Boolean)
      .map((capability) => CAPABILITY_LABELS[capability] || capability.replace(/_/g, " "));
  }

  if (!capabilities || typeof capabilities !== "object") {
    return [];
  }

  return Object.entries(capabilities)
    .filter(([, supported]) => !!supported)
    .map(([capability]) => CAPABILITY_LABELS[capability] || capability.replace(/_/g, " "));
};

const WEBHOOK_EVENT_TYPES = [
  "payment_intent.succeeded",
  "payment_intent.payment_failed",
  "customer.subscription.updated",
  "invoice.payment_succeeded",
  "invoice.payment_failed",
];

const GatewayHealthDashboard = () => {
  const [loading, setLoading] = useState(true);
  const [gateways, setGateways] = useState([]);
  const [webhookLog, setWebhookLog] = useState([]);
  const [webhookLoading, setWebhookLoading] = useState(false);
  const [webhookFilter, setWebhookFilter] = useState("");
  const [webhookEventTypeFilter, setWebhookEventTypeFilter] = useState("");
  const [webhookPage, setWebhookPage] = useState(1);
  const [webhookTotal, setWebhookTotal] = useState(0);
  const [webhookPages, setWebhookPages] = useState(0);
  const [expandedGateway, setExpandedGateway] = useState(null);
  const { toasts, showToast, removeToast } = useToast();
  const { env } = window.arraySubs;

  const fetchGateways = useCallback(async () => {
    setLoading(true);
    try {
      const url = buildUrl(`${env.apiBaseUrl}arraysubs/v1/gateway-health`);
      const response = await fetch(url, {
        headers: { "X-WP-Nonce": env.nonce },
      });

      if (!response.ok) {
        throw new Error(__("Failed to fetch gateway data", "arraysubs"));
      }

      const result = await response.json();
      setGateways(result.data || []);
    } catch (error) {
      showToast(error.message, "error");
    } finally {
      setLoading(false);
    }
  }, [env]);

  const fetchWebhookLog = useCallback(
    async (gateway = "", eventType = "", page = 1) => {
      setWebhookLoading(true);
      try {
        const params = { per_page: 50, page };
        if (gateway) {
          params.gateway = gateway;
        }
        if (eventType) {
          params.event_type = eventType;
        }
        const url = buildUrl(
          `${env.apiBaseUrl}arraysubs/v1/gateway-health/webhook-log`,
          params,
        );
        const response = await fetch(url, {
          headers: { "X-WP-Nonce": env.nonce },
        });

        if (!response.ok) {
          throw new Error(__("Failed to fetch webhook log", "arraysubs"));
        }

        const result = await response.json();
        setWebhookLog(result.data || []);
        setWebhookTotal(result.total || 0);
        setWebhookPages(result.pages || 0);
        setWebhookPage(result.page || 1);
      } catch (error) {
        showToast(error.message, "error");
      } finally {
        setWebhookLoading(false);
      }
    },
    [env],
  );

  useEffect(() => {
    fetchGateways();
    fetchWebhookLog();
  }, []);

  const handleFilterChange = (slug) => {
    setWebhookFilter(slug);
    fetchWebhookLog(slug, webhookEventTypeFilter, 1);
  };

  const handleEventTypeFilterChange = (eventType) => {
    setWebhookEventTypeFilter(eventType);
    fetchWebhookLog(webhookFilter, eventType, 1);
  };

  const getStatusIcon = (gateway) => {
    if (!gateway.enabled) {
      return <XCircle size={18} className="arraysubs-gw-icon--disabled" />;
    }
    if (gateway.needs_setup) {
      return <AlertTriangle size={18} className="arraysubs-gw-icon--warning" />;
    }
    if (gateway.available) {
      return <CheckCircle size={18} className="arraysubs-gw-icon--ok" />;
    }
    return <AlertTriangle size={18} className="arraysubs-gw-icon--warning" />;
  };

  const getStatusText = (gateway) => {
    if (!gateway.enabled) {
      return __("Disabled", "arraysubs");
    }
    if (gateway.needs_setup) {
      return __("Needs Setup", "arraysubs");
    }
    if (gateway.available) {
      return gateway.test_mode
        ? __("Connected (Test Mode)", "arraysubs")
        : __("Connected", "arraysubs");
    }
    return __("Unavailable", "arraysubs");
  };

  const formatTimestamp = (ts) => {
    if (!ts) {
      return __("Never", "arraysubs");
    }

    return formatDateTimeForSite(ts, __("Never", "arraysubs"));
  };

  const renderConfigBadge = (configured) => (
    <span
      className={`arraysubs-gw-config-badge ${
        configured
          ? "arraysubs-gw-config-badge--ok"
          : "arraysubs-gw-config-badge--warning"
      }`}
    >
      {configured ? __("Configured", "arraysubs") : __("Not configured", "arraysubs")}
    </span>
  );

  if (loading) {
    return (
      <DefaultPageLayout title={__("Payment Gateways", "arraysubs")}>
        <div className="arraysubs-loading">
          {__("Loading gateway data...", "arraysubs")}
        </div>
      </DefaultPageLayout>
    );
  }

  return (
    <DefaultPageLayout
      title={__("Payment Gateways", "arraysubs")}
      subtitle={__(
        "Monitor gateway connections, subscription counts, and webhook activity.",
        "arraysubs",
      )}
    >
      <div className="arraysubs-gateway-health">
        {/* Gateway Cards */}
        <div className="arraysubs-gateway-health__cards">
          {gateways.length === 0 ? (
            <div className="arraysubs-gateway-health__empty">
              <Zap size={48} />
              <p>
                {__(
                  "No payment gateways registered. Configure a gateway in WooCommerce Settings to get started.",
                  "arraysubs",
                )}
              </p>
            </div>
          ) : (
            gateways.map((gw) => (
              <div
                key={gw.slug}
                className={`arraysubs-gateway-health__card ${
                  !gw.enabled ? "arraysubs-gateway-health__card--disabled" : ""
                }`}
              >
                <div className="arraysubs-gateway-health__card-header">
                  <div className="arraysubs-gateway-health__card-title">
                    {getStatusIcon(gw)}
                    <h3>{gw.title}</h3>
                    {gw.test_mode && gw.enabled && (
                      <span className="arraysubs-gw-test-badge">
                        {__("Test", "arraysubs")}
                      </span>
                    )}
                  </div>
                  <button
                    type="button"
                    className="button button-small"
                    onClick={() =>
                      setExpandedGateway(
                        expandedGateway === gw.slug ? null : gw.slug,
                      )
                    }
                  >
                    {expandedGateway === gw.slug ? (
                      <ChevronUp size={16} />
                    ) : (
                      <ChevronDown size={16} />
                    )}
                  </button>
                </div>

                <div className="arraysubs-gateway-health__card-stats">
                  <div className="arraysubs-gw-stat">
                    <span className="arraysubs-gw-stat__label">
                      {__("Status", "arraysubs")}
                    </span>
                    <span className="arraysubs-gw-stat__value">
                      {getStatusText(gw)}
                    </span>
                  </div>
                  <div className="arraysubs-gw-stat">
                    <span className="arraysubs-gw-stat__label">
                      <Activity size={14} />
                      {__("Subscriptions", "arraysubs")}
                    </span>
                    <span className="arraysubs-gw-stat__value arraysubs-gw-stat__value--number">
                      {gw.subscription_count}
                    </span>
                  </div>
                  <div className="arraysubs-gw-stat">
                    <span className="arraysubs-gw-stat__label">
                      <Clock size={14} />
                      {__("Last Webhook", "arraysubs")}
                    </span>
                    <span className="arraysubs-gw-stat__value">
                      {formatTimestamp(gw.last_webhook_at)}
                    </span>
                  </div>
                </div>

                {expandedGateway === gw.slug && (
                  <div className="arraysubs-gateway-health__card-details">
                    {gw.description && (
                      <p className="arraysubs-gw-description">
                        {gw.description}
                      </p>
                    )}

                    {gw.webhook_url && (
                      <div className="arraysubs-gw-webhook-url">
                        <strong>{__("Webhook URL:", "arraysubs")}</strong>
                        <code>{gw.webhook_url}</code>
                      </div>
                    )}

                    {gw.slug === "stripe" && gw.stripe && (
                      <div className="arraysubs-gw-stripe-health">
                        <div className="arraysubs-gw-health-row">
                          <strong>
                            {__("Official Woo Stripe webhook:", "arraysubs")}
                          </strong>
                          {renderConfigBadge(gw.stripe.official_webhook_configured)}
                        </div>

                        {gw.stripe.official_webhook_url && (
                          <div className="arraysubs-gw-webhook-url">
                            <strong>
                              {__("Official webhook URL:", "arraysubs")}
                            </strong>
                            <code>{gw.stripe.official_webhook_url}</code>
                          </div>
                        )}

                        <div className="arraysubs-gw-health-row">
                          <strong>
                            {__("ArraySubs secondary webhook:", "arraysubs")}
                          </strong>
                          {renderConfigBadge(
                            gw.stripe.secondary_webhook_configured,
                          )}
                        </div>

                        {gw.stripe.secondary_webhook_url && (
                          <div className="arraysubs-gw-webhook-url">
                            <strong>
                              {__("Secondary webhook URL:", "arraysubs")}
                            </strong>
                            <code>{gw.stripe.secondary_webhook_url}</code>
                          </div>
                        )}

                        <div className="arraysubs-gw-health-row">
                          <strong>
                            {__("Secondary last webhook:", "arraysubs")}
                          </strong>
                          <span>
                            {formatTimestamp(gw.stripe.secondary_last_webhook_at)}
                          </span>
                        </div>
                      </div>
                    )}

                    {getCapabilityTags(gw.capabilities).length > 0 && (
                      <div className="arraysubs-gw-capabilities">
                        <strong>{__("Capabilities:", "arraysubs")}</strong>
                        <div className="arraysubs-gw-capability-tags">
                          {getCapabilityTags(gw.capabilities).map((cap) => (
                            <span
                              key={cap}
                              className="arraysubs-gw-capability-tag"
                            >
                              {cap}
                            </span>
                          ))}
                        </div>
                      </div>
                    )}

                    <div className="arraysubs-gw-actions">
                      <a
                        href={gw.settings_url}
                        className="button button-small"
                        target="_blank"
                        rel="noopener noreferrer"
                      >
                        <ExternalLink size={14} />
                        {__("WooCommerce Settings", "arraysubs")}
                      </a>
                    </div>
                  </div>
                )}
              </div>
            ))
          )}
        </div>

        {/* Webhook Event Log */}
        <div className="arraysubs-gateway-health__log">
          <div className="arraysubs-gateway-health__log-header">
            <h3>
              <Clock size={20} />
              {__("Webhook Event Log", "arraysubs")}
            </h3>
            <div className="arraysubs-gateway-health__log-controls">
              <select
                value={webhookFilter}
                onChange={(e) => handleFilterChange(e.target.value)}
                className="arraysubs-gw-filter-select"
              >
                <option value="">{__("All Gateways", "arraysubs")}</option>
                {gateways.map((gw) => (
                  <option key={gw.slug} value={gw.slug}>
                    {gw.title}
                  </option>
                ))}
              </select>
              <select
                value={webhookEventTypeFilter}
                onChange={(e) => handleEventTypeFilterChange(e.target.value)}
                className="arraysubs-gw-filter-select"
              >
                <option value="">{__("All Event Types", "arraysubs")}</option>
                {WEBHOOK_EVENT_TYPES.map((eventType) => (
                  <option key={eventType} value={eventType}>
                    {eventType}
                  </option>
                ))}
              </select>
              <button
                type="button"
                className="button button-small"
                onClick={() =>
                  fetchWebhookLog(
                    webhookFilter,
                    webhookEventTypeFilter,
                    webhookPage,
                  )
                }
                disabled={webhookLoading}
              >
                <RefreshCw
                  size={14}
                  className={webhookLoading ? "arraysubs-spin" : ""}
                />
                {__("Refresh", "arraysubs")}
              </button>
            </div>
          </div>

          <div className="arraysubs-gateway-health__log-body">
            {webhookLoading && webhookLog.length === 0 ? (
              <p className="arraysubs-loading">
                {__("Loading webhook events...", "arraysubs")}
              </p>
            ) : webhookLog.length === 0 ? (
              <p className="arraysubs-gateway-health__log-empty">
                {__("No webhook events recorded yet.", "arraysubs")}
              </p>
            ) : (
              <>
                <table className="wp-list-table widefat fixed striped">
                  <thead>
                    <tr>
                      <th>{__("Gateway", "arraysubs")}</th>
                      <th>{__("Event ID", "arraysubs")}</th>
                      <th>{__("Event Type", "arraysubs")}</th>
                      <th>{__("Processed At", "arraysubs")}</th>
                    </tr>
                  </thead>
                  <tbody>
                    {webhookLog.map((event, index) => (
                      <tr key={`${event.event_id}-${index}`}>
                        <td>
                          <span className="arraysubs-gw-slug-badge">
                            {event.gateway_slug}
                          </span>
                        </td>
                        <td>
                          <code className="arraysubs-gw-event-id">
                            {event.event_id}
                          </code>
                        </td>
                        <td>{event.event_type || "-"}</td>
                        <td>{formatTimestamp(event.processed_at)}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>

                {/* Pagination */}
                {webhookPages > 1 && (
                  <div className="arraysubs-gateway-health__log-pagination">
                    <button
                      type="button"
                      className="button button-small"
                      disabled={webhookPage <= 1}
                      onClick={() =>
                        fetchWebhookLog(
                          webhookFilter,
                          webhookEventTypeFilter,
                          webhookPage - 1,
                        )
                      }
                    >
                      {__("Previous", "arraysubs")}
                    </button>
                    <span>
                      {/* translators: 1: current page, 2: total pages */}
                      {__(
                        `Page ${webhookPage} of ${webhookPages}`,
                        "arraysubs",
                      )}
                    </span>
                    <button
                      type="button"
                      className="button button-small"
                      disabled={webhookPage >= webhookPages}
                      onClick={() =>
                        fetchWebhookLog(
                          webhookFilter,
                          webhookEventTypeFilter,
                          webhookPage + 1,
                        )
                      }
                    >
                      {__("Next", "arraysubs")}
                    </button>
                  </div>
                )}
              </>
            )}
          </div>
          {webhookTotal > 0 && (
            <div className="arraysubs-gateway-health__log-footer">
              {/* translators: %d: total number of events */}
              {__(`${webhookTotal} total events`, "arraysubs")}
            </div>
          )}
        </div>
      </div>

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

export default GatewayHealthDashboard;
