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 GatewayHealthDashboard = () => {
  const [loading, setLoading] = useState(true);
  const [gateways, setGateways] = useState([]);
  const [webhookLog, setWebhookLog] = useState([]);
  const [webhookLoading, setWebhookLoading] = useState(false);
  const [webhookFilter, setWebhookFilter] = 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 = "", page = 1) => {
      setWebhookLoading(true);
      try {
        const params = { per_page: 50, page };
        if (gateway) {
          params.gateway = gateway;
        }
        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, 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"));
  };

  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.capabilities && gw.capabilities.length > 0 && (
                      <div className="arraysubs-gw-capabilities">
                        <strong>{__("Capabilities:", "arraysubs")}</strong>
                        <div className="arraysubs-gw-capability-tags">
                          {gw.capabilities.map((cap) => (
                            <span
                              key={cap}
                              className="arraysubs-gw-capability-tag"
                            >
                              {cap.replace(/_/g, " ")}
                            </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>
              <button
                type="button"
                className="button button-small"
                onClick={() => fetchWebhookLog(webhookFilter, 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, 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, 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;
