import React, { useState, useEffect } from "react";
import { useParams, Link, useNavigate } from "react-router-dom";
import { __ } from "@wordpress/i18n";
import DefaultPageLayout from "@/components/DefaultPageLayout";
import CancelModal from "@/components/CancelModal";
import CancellationDetailsCard from "@/components/CancellationDetailsCard";
import SkipPauseCard from "@/components/SkipPauseCard";
import PaymentTimeline from "@/components/PaymentTimeline";
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 { buildUrl } from "@/libs/url";
import { getDisplayDate } from "@/libs/dateTime";
import { NotesPanel } from "@/components/SubscriptionNotes";
import {
  User,
  Package,
  CreditCard,
  Calendar,
  MapPin,
  FileText,
  History,
  XCircle,
  RefreshCw,
  Clock,
  Zap,
  Unlink,
  Ticket,
  LogIn,
  DollarSign,
} from "lucide-react";

const SubscriptionDetail = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(true);
  const [data, setData] = useState(null);
  const [cancelModalOpen, setCancelModalOpen] = useState(false);
  const [detachProcessing, setDetachProcessing] = useState(false);
  const [retryProcessing, setRetryProcessing] = useState(false);
  const [pendingSwitchProcessing, setPendingSwitchProcessing] = useState(false);
  const [syncProcessing, setSyncProcessing] = useState(false);
  const [proratedModalOpen, setProratedModalOpen] = useState(false);
  const [proratedPreview, setProratedPreview] = useState(null);
  const [proratedPreviewLoading, setProratedPreviewLoading] = useState(false);
  const [proratedProcessing, setProratedProcessing] = useState(false);
  const [proratedError, setProratedError] = useState("");
  const [proratedReason, setProratedReason] = useState("");
  const [proratedCancelAfter, setProratedCancelAfter] = useState(true);
  const { toasts, showToast, removeToast } = useToast();
  const { confirm, confirmDialog } = useConfirm();
  const { env } = window.arraySubs;

  useEffect(() => {
    fetchData();
  }, [id]);

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

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

      const result = await response.json();
      setData(result.content);
    } catch (error) {
      console.error("Error:", error);
      showToast(error.message, "error");
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return (
      <DefaultPageLayout title={__("Loading...", "arraysubs")}>
        <div className="arraysubs-loading">
          {__("Loading subscription details...", "arraysubs")}
        </div>
      </DefaultPageLayout>
    );
  }

  if (!data) {
    return (
      <DefaultPageLayout title={__("Not Found", "arraysubs")}>
        <p>{__("Subscription not found.", "arraysubs")}</p>
        <Link to="/subscriptions" className="button">
          {__("Back to Subscriptions", "arraysubs")}
        </Link>
      </DefaultPageLayout>
    );
  }

  const formatDate = (displayDate, rawDate) =>
    getDisplayDate(displayDate, rawDate);

  const formatCurrency = (amount) => {
    return new Intl.NumberFormat("en-US", {
      style: "currency",
      currency: data.currency || "USD",
    }).format(amount);
  };

  const getStatusLabel = (status) => {
    const labels = {
      "arraysubs-pending": __("Pending", "arraysubs"),
      "arraysubs-active": __("Active", "arraysubs"),
      "arraysubs-on-hold": __("On Hold", "arraysubs"),
      "arraysubs-cancelled": __("Cancelled", "arraysubs"),
      "arraysubs-expired": __("Expired", "arraysubs"),
      "arraysubs-trial": __("Trial", "arraysubs"),
    };
    return labels[status] || status;
  };

  const getStatusClass = (status) => {
    const classes = {
      "arraysubs-pending": "status-pending",
      "arraysubs-active": "status-active",
      "arraysubs-on-hold": "status-on-hold",
      "arraysubs-cancelled": "status-cancelled",
      "arraysubs-expired": "status-expired",
      "arraysubs-trial": "status-trial",
    };
    return classes[status] || "";
  };

  // Check if subscription can be cancelled
  const canCancel = () => {
    const cancellableStatuses = [
      "arraysubs-active",
      "arraysubs-on-hold",
      "arraysubs-trial",
      "arraysubs-pending",
    ];
    return data && cancellableStatuses.includes(data.status);
  };

  // Handle cancellation
  const handleCancelSubscription = async ({
    cancel_type,
    reason,
    reason_details,
  }) => {
    try {
      const response = await fetch(
        `${env.apiBaseUrl}arraysubs/v1/subscriptions/${id}/cancel`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            "X-WP-Nonce": env.nonce,
          },
          body: JSON.stringify({
            cancel_type,
            reason,
            reason_details,
          }),
        },
      );

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(
          errorData.message || __("Failed to cancel subscription", "arraysubs"),
        );
      }

      const result = await response.json();
      showToast(result.message, "success");

      // Refresh data to show updated status
      fetchData();
    } catch (error) {
      console.error("Cancel error:", error);
      showToast(error.message, "error");
      throw error; // Re-throw to let modal know it failed
    }
  };

  // Handle undo cancellation
  const handleUndoCancellation = async () => {
    try {
      await confirm({
        title: __("Undo Scheduled Cancellation", "arraysubs"),
        message: __(
          "Are you sure you want to undo the scheduled cancellation? The subscription will continue renewing normally.",
          "arraysubs",
        ),
        confirmText: __("Undo Cancellation", "arraysubs"),
        loadingText: __("Removing…", "arraysubs"),
        variant: "info",
        onConfirm: async () => {
          const response = await fetch(
            `${env.apiBaseUrl}arraysubs/v1/subscriptions/${id}/undo-cancellation`,
            {
              method: "POST",
              headers: {
                "Content-Type": "application/json",
                "X-WP-Nonce": env.nonce,
              },
            },
          );

          if (!response.ok) {
            const errorData = await response.json();
            throw new Error(
              errorData.message ||
                __("Failed to undo cancellation", "arraysubs"),
            );
          }

          const result = await response.json();
          showToast(
            result.message ||
              __("Scheduled cancellation removed", "arraysubs"),
            "success",
          );
          fetchData();
        },
      });
    } catch (error) {
      console.error("Undo cancellation error:", error);
      showToast(error.message, "error");
    }
  };

  // Handle gateway detach
  const handleDetachGateway = async () => {
    try {
      await confirm({
        title: __("Detach Payment Gateway", "arraysubs"),
        message: __(
          "Are you sure you want to detach the payment gateway? The subscription will revert to manual payment.",
          "arraysubs",
        ),
        confirmText: __("Detach Gateway", "arraysubs"),
        loadingText: __("Detaching…", "arraysubs"),
        variant: "danger",
        onConfirm: async () => {
          setDetachProcessing(true);
          try {
            const response = await fetch(
              buildUrl(
                `${env.apiBaseUrl}arraysubs/v1/gateway-health/detach/${id}`,
              ),
              {
                method: "POST",
                headers: {
                  "Content-Type": "application/json",
                  "X-WP-Nonce": env.nonce,
                },
              },
            );

            const result = await response.json();

            if (!response.ok) {
              throw new Error(
                result.message ||
                  __("Failed to detach gateway", "arraysubs"),
              );
            }

            showToast(
              result.message ||
                __("Gateway detached successfully", "arraysubs"),
              "success",
            );
            fetchData();
          } finally {
            setDetachProcessing(false);
          }
        },
      });
    } catch (error) {
      console.error("Detach gateway error:", error);
      showToast(error.message, "error");
    }
  };

  // Handle manual renewal payment retry
  const handleRetryPayment = async () => {
    try {
      await confirm({
        title: __("Retry Renewal Payment", "arraysubs"),
        message: __(
          "Retry the failed renewal charge now? The plugin will first verify with the gateway whether the customer was already charged before attempting a new payment.",
          "arraysubs",
        ),
        confirmText: __("Retry Payment", "arraysubs"),
        loadingText: __("Retrying…", "arraysubs"),
        variant: "warning",
        onConfirm: async () => {
          setRetryProcessing(true);
          try {
            const response = await fetch(
              `${env.apiBaseUrl}arraysubs/v1/subscriptions/${id}/retry-payment`,
              {
                method: "POST",
                headers: {
                  "Content-Type": "application/json",
                  "X-WP-Nonce": env.nonce,
                },
              },
            );

            const result = await response.json();

            if (!response.ok) {
              throw new Error(
                result.message ||
                  __("Renewal payment retry failed.", "arraysubs"),
              );
            }

            showToast(
              result.message || __("Renewal payment retried.", "arraysubs"),
              "success",
            );
            fetchData();
          } finally {
            setRetryProcessing(false);
          }
        },
      });
    } catch (error) {
      console.error("Retry payment error:", error);
      showToast(error.message, "error");
    }
  };

  // Handle pending plan switch cancellation
  const handleCancelPendingSwitch = async () => {
    try {
      await confirm({
        title: __("Cancel Pending Plan Switch", "arraysubs"),
        message: __(
          "Cancel the pending plan switch? The next renewal will continue with the current plan.",
          "arraysubs",
        ),
        confirmText: __("Cancel Pending Switch", "arraysubs"),
        cancelText: __("Keep Switch", "arraysubs"),
        loadingText: __("Cancelling…", "arraysubs"),
        variant: "warning",
        onConfirm: async () => {
          setPendingSwitchProcessing(true);
          try {
            const response = await fetch(
              buildUrl(
                `${env.apiBaseUrl}arraysubs/v1/subscriptions/${id}/pending-switch/cancel`,
              ),
              {
                method: "POST",
                headers: {
                  "Content-Type": "application/json",
                  "X-WP-Nonce": env.nonce,
                },
              },
            );

            const result = await response.json();

            if (!response.ok) {
              throw new Error(
                result.message ||
                  __("Failed to cancel pending switch.", "arraysubs"),
              );
            }

            showToast(
              result.message ||
                __("Pending plan switch cancelled.", "arraysubs"),
              "success",
            );
            fetchData();
          } finally {
            setPendingSwitchProcessing(false);
          }
        },
      });
    } catch (error) {
      console.error("Cancel pending switch error:", error);
      showToast(error.message, "error");
    }
  };

  // Handle gateway sync
  const handleGatewaySync = async () => {
    setSyncProcessing(true);
    try {
      const response = await fetch(
        `${env.apiBaseUrl}arraysubs/v1/subscriptions/${id}/gateway-sync`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            "X-WP-Nonce": env.nonce,
          },
        },
      );

      const result = await response.json();

      if (!response.ok) {
        throw new Error(
          result.message || __("Gateway sync failed.", "arraysubs"),
        );
      }

      const changes = result.content?.changes || [];
      const summary =
        changes.length > 0
          ? `${result.message || ""} (${changes.length} change${changes.length === 1 ? "" : "s"})`
          : result.message || __("No changes needed; local state matches gateway.", "arraysubs");

      showToast(summary, "success");
      fetchData();
    } catch (error) {
      console.error("Gateway sync error:", error);
      showToast(error.message, "error");
    } finally {
      setSyncProcessing(false);
    }
  };

  const formatDayCount = (value) => {
    const numberValue = Number(value);
    if (!Number.isFinite(numberValue)) {
      return "0";
    }

    return numberValue.toLocaleString(undefined, {
      minimumFractionDigits: 0,
      maximumFractionDigits: 2,
    });
  };

  const getProratedPreviewAmount = () => {
    if (!proratedPreview) {
      return "";
    }

    return Number(proratedPreview.refund_amount ?? proratedPreview.amount ?? 0)
      .toFixed(2);
  };

  const handleOpenProratedRefund = async () => {
    setProratedModalOpen(true);
    setProratedReason("");
    setProratedCancelAfter(true);
    setProratedError("");
    setProratedPreview(actions.prorated_refund?.available ? actions.prorated_refund : null);
    setProratedPreviewLoading(true);

    try {
      const response = await fetch(
        `${env.apiBaseUrl}arraysubs/v1/subscriptions/${id}/prorated-refund-preview`,
        {
          headers: {
            "Content-Type": "application/json",
            "X-WP-Nonce": env.nonce,
          },
        },
      );
      const result = await response.json();

      if (!response.ok || result.code !== 200) {
        throw new Error(
          result.message ||
            __("Failed to calculate prorated refund preview.", "arraysubs"),
        );
      }

      setProratedPreview(result.content);
    } catch (error) {
      console.error("Prorated refund preview error:", error);
      setProratedError(error.message);
      showToast(error.message, "error");
    } finally {
      setProratedPreviewLoading(false);
    }
  };

  const handleCloseProratedRefund = () => {
    if (!proratedProcessing) {
      setProratedModalOpen(false);
      setProratedError("");
    }
  };

  const handleProcessProratedRefund = async () => {
    setProratedProcessing(true);

    try {
      const response = await fetch(
        `${env.apiBaseUrl}arraysubs/v1/subscriptions/${id}/prorated-refund`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            "X-WP-Nonce": env.nonce,
          },
          body: JSON.stringify({
            reason: proratedReason.trim(),
            cancel_after: proratedCancelAfter,
          }),
        },
      );
      const result = await response.json();

      if (!response.ok || result.code !== 200) {
        throw new Error(
          result.message || __("Failed to process prorated refund.", "arraysubs"),
        );
      }

      showToast(
        result.message || __("Prorated refund processed.", "arraysubs"),
        "success",
      );
      setProratedModalOpen(false);
      fetchData();
    } catch (error) {
      console.error("Prorated refund processing error:", error);
      showToast(error.message, "error");
    } finally {
      setProratedProcessing(false);
    }
  };

  // The REST endpoint exposes computed action availability under
  // `actions`. Pro extends `gateway_info` via the
  // `arraysubs_subscription_detail_data` filter. The Resync action lives
  // inside the Payment Gateway card when the gateway is automatic and
  // supports sync; it is no longer duplicated in the page header.
  const actions = data.actions || {};
  const gatewayInfo = data.gateway_info || {};
  const pendingSwitch = data.pending_switch || null;
  const hasFailedRenewal = !!actions.can_retry_payment;
  const isAutomaticGateway = gatewayInfo.is_automatic === true;
  const hasFeatureManager = (window.arraySubs?.liveBootClasses || []).some(
    (className) => className.includes("Features\\FeatureManager\\"),
  );
  const canViewFeatureLog = hasFeatureManager && data.customer_id > 0;
  const canResyncGateway =
    isAutomaticGateway &&
    !!actions.can_sync_gateway &&
    gatewayInfo.supports_sync === true;

  return (
    <DefaultPageLayout
      title={`${__("Subscription", "arraysubs")} #${data.id}`}
      subtitle={data.title}
    >
      <div className="arraysubs-subscription-detail">
        {/* Header Actions */}
        <div className="detail-header">
          <div className="detail-header__status">
            <span className={`status-badge ${getStatusClass(data.status)}`}>
              {getStatusLabel(data.status)}
            </span>
            {data.meta?._waiting_cancellation && (
              <span className="status-badge status-waiting-cancel">
                <Clock size={12} style={{ marginRight: "4px" }} />
                {__("Cancels at end of period", "arraysubs")}
              </span>
            )}
            {pendingSwitch && (
              <span className="status-badge status-pending-switch">
                <RefreshCw size={12} style={{ marginRight: "4px" }} />
                {__("Plan switch at next renewal", "arraysubs")}
              </span>
            )}
          </div>
          <div className="detail-header__actions">
            {data.meta?._waiting_cancellation ? (
              <button
                type="button"
                className="button"
                onClick={handleUndoCancellation}
              >
                <RefreshCw size={16} style={{ marginRight: "6px" }} />
                {__("Undo Scheduled Cancellation", "arraysubs")}
              </button>
            ) : (
              canCancel() && (
                <button
                  type="button"
                  className="button arraysubs-btn--danger"
                  onClick={() => setCancelModalOpen(true)}
                >
                  <XCircle size={16} style={{ marginRight: "6px" }} />
                  {__("Cancel Subscription", "arraysubs")}
                </button>
              )
            )}
            {actions.can_prorated_refund && (
              <SpinnerButton
                type="button"
                className="button"
                onClick={handleOpenProratedRefund}
                loading={proratedPreviewLoading}
                loadingText={__("Previewing…", "arraysubs")}
                title={__(
                  "Preview and process a prorated refund for unused time.",
                  "arraysubs",
                )}
              >
                <DollarSign size={16} style={{ marginRight: "6px" }} />
                {__("Prorated Refund", "arraysubs")}
              </SpinnerButton>
            )}
            {hasFailedRenewal && (
              <SpinnerButton
                type="button"
                className="button"
                onClick={handleRetryPayment}
                loading={retryProcessing}
                loadingText={__("Retrying…", "arraysubs")}
                title={__(
                  "Retry the failed renewal payment. The plugin verifies with the gateway first.",
                  "arraysubs",
                )}
              >
                <RefreshCw size={16} style={{ marginRight: "6px" }} />
                {__("Retry Payment", "arraysubs")}
              </SpinnerButton>
            )}
            {pendingSwitch && (
              <SpinnerButton
                type="button"
                className="button"
                onClick={handleCancelPendingSwitch}
                loading={pendingSwitchProcessing}
                loadingText={__("Cancelling…", "arraysubs")}
                title={__(
                  "Cancel the pending plan switch. Current plan will continue at the next renewal.",
                  "arraysubs",
                )}
              >
                <XCircle size={16} style={{ marginRight: "6px" }} />
                {__("Cancel Pending Switch", "arraysubs")}
              </SpinnerButton>
            )}
            <Link
              to={`/subscriptions/edit/${id}`}
              className="button button-primary"
            >
              {__("Edit Subscription", "arraysubs")}
            </Link>
            {canViewFeatureLog && (
              <Link
                to={`/subscriptions/feature-log?user_id=${data.customer_id}`}
                className="button"
              >
                <History size={16} style={{ marginRight: "6px" }} />
                {__("Feature Log", "arraysubs")}
              </Link>
            )}
            {data.customer_id > 0 &&
              (data.login_as_user_url ? (
                <a
                  href={buildUrl(data.login_as_user_url, {
                    back_url: window.location.href,
                  })}
                  className="button"
                >
                  <LogIn size={16} style={{ marginRight: "6px" }} />
                  {__("Login as Customer", "arraysubs")}
                </a>
              ) : (
                <button
                  type="button"
                  className="button"
                  disabled
                  title={data.login_as_user_reason || ""}
                >
                  <LogIn size={16} style={{ marginRight: "6px" }} />
                  {__("Login as Customer", "arraysubs")}
                </button>
              ))}
          </div>
        </div>

        {/* Main Grid */}
        <div className="detail-grid">
          {/* Subscription Info */}
          <div className="detail-card">
            <div className="detail-card__header">
              <Calendar size={20} />
              <h3>{__("Subscription", "arraysubs")}</h3>
            </div>
            <div className="detail-card__body">
              <div className="info-list">
                <div className="info-item">
                  <strong>{__("Subscription ID:", "arraysubs")}</strong>#
                  {data.id}
                </div>
                <div className="info-item">
                  <strong>{__("Created:", "arraysubs")}</strong>
                  {formatDate(
                    data.created_date_display,
                    data.created_date_gmt ||
                      data.created_date ||
                      data.start_date,
                  )}
                </div>
                <div className="info-item">
                  <strong>{__("Start Date:", "arraysubs")}</strong>
                  {formatDate(data.start_date_display, data.start_date)}
                </div>
                <div className="info-item">
                  {data.meta?._waiting_cancellation ? (
                    <>
                      <strong>{__("Cancels On:", "arraysubs")}</strong>
                      {formatDate(
                        data.cancellation?.scheduled_date_display,
                        data.cancellation?.scheduled_date ||
                          data.next_payment_date,
                      )}
                    </>
                  ) : (
                    <>
                      <strong>{__("Next Payment:", "arraysubs")}</strong>
                      {data.billing_period === "lifetime"
                        ? __("No recurring payment", "arraysubs")
                        : formatDate(
                            data.next_payment_date_display,
                            data.next_payment_date,
                          )}
                    </>
                  )}
                </div>
                {data.last_payment_date && (
                  <div className="info-item">
                    <strong>{__("Last Payment:", "arraysubs")}</strong>
                    {formatDate(
                      data.last_payment_date_display,
                      data.last_payment_date,
                    )}
                  </div>
                )}
                <div className="info-item">
                  <strong>{__("Total Paid:", "arraysubs")}</strong>
                  {formatCurrency(data.total_paid ?? 0)}
                </div>
                {data.trial_length > 0 && (
                  <>
                    <div className="info-item">
                      <strong>{__("Trial Length:", "arraysubs")}</strong>
                      {data.trial_length} {data.trial_period}(s)
                    </div>
                    {data.trial_end_date && (
                      <div className="info-item">
                        <strong>{__("Trial Ends:", "arraysubs")}</strong>
                        {formatDate(
                          data.trial_end_date_display,
                          data.trial_end_date,
                        )}
                      </div>
                    )}
                  </>
                )}
                {data.end_date && (
                  <div className="info-item">
                    <strong>{__("End Date:", "arraysubs")}</strong>
                    {formatDate(data.end_date_display, data.end_date)}
                  </div>
                )}
              </div>
            </div>
          </div>

          {/* Cancellation Details */}
          <CancellationDetailsCard
            cancellation={data.cancellation}
            status={data.status}
          />

          {pendingSwitch && (
            <div className="detail-card">
              <div className="detail-card__header">
                <RefreshCw size={20} />
                <h3>{__("Pending Plan Switch", "arraysubs")}</h3>
              </div>
              <div className="detail-card__body">
                <div className="info-list">
                  <div className="info-item">
                    <strong>{__("Target Plan:", "arraysubs")}</strong>
                    {pendingSwitch.target_product_name}
                  </div>
                  <div className="info-item">
                    <strong>{__("Switch Type:", "arraysubs")}</strong>
                    {pendingSwitch.switch_type}
                  </div>
                  <div className="info-item">
                    <strong>{__("Effective Date:", "arraysubs")}</strong>
                    {formatDate(
                      pendingSwitch.effective_renewal_date_display,
                      pendingSwitch.effective_renewal_date,
                    )}
                  </div>
                  <div className="info-item">
                    <strong>{__("Quantity:", "arraysubs")}</strong>
                    {pendingSwitch.quantity}
                  </div>
                  <div className="info-item">
                    <strong>{__("Target Unit Price:", "arraysubs")}</strong>
                    {pendingSwitch.formatted_unit_price ||
                      formatCurrency(pendingSwitch.target_unit_price || 0)}
                  </div>
                  <div className="info-item">
                    <strong>{__("Future Line Total:", "arraysubs")}</strong>
                    {pendingSwitch.formatted_line_total ||
                      formatCurrency(pendingSwitch.target_line_total || 0)}
                  </div>
                  <div className="info-item">
                    <strong>{__("Switch Fee:", "arraysubs")}</strong>
                    {pendingSwitch.formatted_switch_fee ||
                      formatCurrency(pendingSwitch.switch_fee_total || 0)}
                  </div>
                  <div className="info-item">
                    <strong>{__("Requested By:", "arraysubs")}</strong>
                    {pendingSwitch.requested_by}
                  </div>
                  {pendingSwitch.requested_at && (
                    <div className="info-item">
                      <strong>{__("Requested At:", "arraysubs")}</strong>
                      {formatDate(
                        pendingSwitch.requested_at_display,
                        pendingSwitch.requested_at,
                      )}
                    </div>
                  )}
                </div>
              </div>
            </div>
          )}

          {/* Skip & Pause */}
          <SkipPauseCard
            subscriptionId={parseInt(id)}
            subscriptionStatus={data.status}
            onUpdate={fetchData}
            showToast={showToast}
          />

          {/* Customer Info */}
          <div className="detail-card">
            <div className="detail-card__header">
              <User size={20} />
              <h3>{__("Customer Information", "arraysubs")}</h3>
            </div>
            <div className="detail-card__body">
              {data.customer ? (
                <div className="info-list">
                  <div className="info-item">
                    <strong>{__("Name:", "arraysubs")}</strong>
                    <Link to={`/customers/${data.customer.id}`}>
                      {data.customer.display_name}
                    </Link>
                  </div>
                  <div className="info-item">
                    <strong>{__("Email:", "arraysubs")}</strong>
                    <a href={`mailto:${data.customer.email}`}>
                      {data.customer.email}
                    </a>
                  </div>
                  <div className="info-item">
                    <strong>{__("Invoice Email:", "arraysubs")}</strong>
                    {data.invoice_email || data.customer_email}
                  </div>
                  <div className="info-item">
                    <strong>{__("Registered:", "arraysubs")}</strong>
                    {formatDate(
                      data.customer.registered_display,
                      data.customer.registered,
                    )}
                  </div>
                </div>
              ) : (
                <p>{__("Customer information not available", "arraysubs")}</p>
              )}
            </div>
          </div>

          {/* Product Info */}
          <div className="detail-card">
            <div className="detail-card__header">
              <Package size={20} />
              <h3>{__("Product", "arraysubs")}</h3>
            </div>
            <div className="detail-card__body">
              {data.product ? (
                <div className="product-info">
                  {data.product.image && (
                    <img
                      src={data.product.image}
                      alt={data.product.name}
                      className="product-image"
                    />
                  )}
                  <div className="info-list">
                    <div className="info-item">
                      <strong>{__("Name:", "arraysubs")}</strong>
                      <a
                        href={data.product.permalink}
                        target="_blank"
                        rel="noopener noreferrer"
                      >
                        {data.product.parent_name || data.product.name}
                      </a>
                    </div>
                    {data.product.variation_attributes &&
                      data.product.variation_attributes.length > 0 && (
                        <>
                          {data.product.variation_attributes.map(
                            (attr, index) => (
                              <div className="info-item" key={index}>
                                <strong>{attr.name}:</strong>
                                {attr.value}
                              </div>
                            ),
                          )}
                        </>
                      )}
                    <div className="info-item">
                      <strong>{__("SKU:", "arraysubs")}</strong>
                      {data.product.sku || "-"}
                    </div>
                    <div className="info-item">
                      <strong>{__("Quantity:", "arraysubs")}</strong>
                      {data.quantity}
                    </div>
                  </div>
                </div>
              ) : (
                <p>{__("Product not found", "arraysubs")}</p>
              )}
            </div>
          </div>

          {/* Billing Info */}
          <div className="detail-card">
            <div className="detail-card__header">
              <CreditCard size={20} />
              <h3>{__("Billing Information", "arraysubs")}</h3>
            </div>
            <div className="detail-card__body">
              <div className="info-list">
                <div className="info-item">
                  <strong>{__("Recurring Amount:", "arraysubs")}</strong>
                  {formatCurrency(
                    data.effective_recurring_amount ?? data.recurring_amount,
                  )}
                </div>
                {data.active_retention_discount &&
                  (data.effective_recurring_amount ?? data.recurring_amount) <
                    (data.base_recurring_amount ?? data.recurring_amount) && (
                    <>
                      <div className="info-item">
                        <strong>
                          {__("Base Renewal Amount:", "arraysubs")}
                        </strong>
                        {formatCurrency(
                          data.base_recurring_amount ?? data.recurring_amount,
                        )}
                      </div>
                      <div className="info-item">
                        <strong>
                          {__("Retention Discount:", "arraysubs")}
                        </strong>
                        {data.active_retention_discount.type === "percent"
                          ? `${data.active_retention_discount.amount}%`
                          : formatCurrency(
                              data.active_retention_discount.amount,
                            )}
                        {" — "}
                        {(data.active_retention_discount.remaining || 0) === 1
                          ? __("1 renewal remaining", "arraysubs")
                          : `${
                              data.active_retention_discount.remaining || 0
                            } ${__("renewals remaining", "arraysubs")}`}
                      </div>
                    </>
                  )}
                {data.different_renewal_price > 0 && (
                  <>
                    <div className="info-item">
                      <strong>
                        {__("Different Renewal Price:", "arraysubs")}
                      </strong>
                      {formatCurrency(data.different_renewal_price)}
                    </div>
                    <div className="info-item">
                      <strong>{__("Applies After:", "arraysubs")}</strong>
                      {data.different_renewal_price_after}{" "}
                      {__("payments", "arraysubs")}
                    </div>
                  </>
                )}
                <div className="info-item">
                  <strong>{__("Billing Schedule:", "arraysubs")}</strong>
                  {data.billing_period === "lifetime" ? (
                    __("Lifetime Deal", "arraysubs")
                  ) : (
                    <>
                      {__("Every", "arraysubs")} {data.billing_interval}{" "}
                      {data.billing_period}(s)
                    </>
                  )}
                </div>
                {data.signup_fee > 0 && (
                  <div className="info-item">
                    <strong>{__("Signup Fee:", "arraysubs")}</strong>
                    {formatCurrency(data.signup_fee)}
                  </div>
                )}
                <div className="info-item">
                  <strong>{__("Completed Payments:", "arraysubs")}</strong>
                  {data.completed_payments}
                </div>
                <div className="info-item">
                  <strong>{__("Payment Method:", "arraysubs")}</strong>
                  {data.payment_method_title || data.payment_method || "-"}
                </div>
              </div>
            </div>
          </div>

          {Array.isArray(data.checkout_builder_fields) &&
            data.checkout_builder_fields.length > 0 && (
              <div className="detail-card">
                <div className="detail-card__header">
                  <FileText size={20} />
                  <h3>{__("Checkout Builder Fields", "arraysubs")}</h3>
                </div>
                <div className="detail-card__body">
                  <div className="info-list">
                    {data.checkout_builder_fields.map((field) => (
                      <div className="info-item" key={field.key}>
                        <strong>{field.label}:</strong>
                        {field.value}
                      </div>
                    ))}
                  </div>
                </div>
              </div>
            )}

          {/* Coupon Discount Card */}
          {data.coupon && (
            <div className="detail-card arraysubs-coupon-card">
              <div className="detail-card__header">
                <Ticket size={20} />
                <h3>{__("Coupon Discount", "arraysubs")}</h3>
                {data.coupon.is_expired ? (
                  <span className="arraysubs-coupon-badge arraysubs-coupon-badge--expired">
                    {__("Expired", "arraysubs")}
                  </span>
                ) : (
                  <span className="arraysubs-coupon-badge arraysubs-coupon-badge--active">
                    {data.coupon.discount_type === "recurring"
                      ? __("Recurring", "arraysubs")
                      : __("One-time", "arraysubs")}
                  </span>
                )}
              </div>
              <div className="detail-card__body">
                <div className="info-list">
                  <div className="info-item">
                    <strong>{__("Coupon Code:", "arraysubs")}</strong>
                    <code>{data.coupon.code}</code>
                    {!data.coupon.coupon_exists && (
                      <em className="arraysubs-coupon-deleted">
                        {" "}
                        ({__("coupon deleted", "arraysubs")})
                      </em>
                    )}
                  </div>
                  <div className="info-item">
                    <strong>{__("Discount:", "arraysubs")}</strong>
                    {data.coupon.discount_percent > 0
                      ? `${data.coupon.discount_percent}%`
                      : formatCurrency(data.coupon.discount_amount)}
                  </div>
                  {data.coupon.discount_type === "recurring" && (
                    <>
                      {data.coupon.is_unlimited ? (
                        <div className="info-item">
                          <strong>{__("Cycle Limit:", "arraysubs")}</strong>
                          {__(
                            "Unlimited (applies to all renewals)",
                            "arraysubs",
                          )}
                        </div>
                      ) : (
                        <>
                          <div className="info-item">
                            <strong>{__("Total Cycles:", "arraysubs")}</strong>
                            {data.coupon.original_cycles}
                            {data.coupon.count_initial && (
                              <em>
                                {" "}
                                ({__("includes initial checkout", "arraysubs")})
                              </em>
                            )}
                          </div>
                          <div className="info-item">
                            <strong>
                              {__("Remaining Cycles:", "arraysubs")}
                            </strong>
                            {data.coupon.remaining_cycles}
                          </div>
                        </>
                      )}
                    </>
                  )}
                  {data.coupon.captured_at_display && (
                    <div className="info-item">
                      <strong>{__("Captured:", "arraysubs")}</strong>
                      {data.coupon.captured_at_display}
                    </div>
                  )}
                </div>
              </div>
            </div>
          )}

          {/* Gateway Payment Method Card — only for automatic gateways. */}
          {/* Manual gateways (bacs/cheque/cod) have no remote state worth */}
          {/* surfacing; the gateway slug already shows in Order Summary. */}
          {isAutomaticGateway && (
            <div className="detail-card arraysubs-gateway-card">
              <div className="detail-card__header">
                <Zap size={20} />
                <h3>{__("Payment Gateway", "arraysubs")}</h3>
                <span
                  className={`arraysubs-gateway-badge arraysubs-gateway-badge--${data.gateway_info.status}`}
                >
                  {data.gateway_info.status === "detached"
                    ? __("Detached", "arraysubs")
                    : data.gateway_info.status === "errored"
                    ? __("Error", "arraysubs")
                    : __("Connected", "arraysubs")}
                </span>
              </div>
              <div className="detail-card__body">
                <div className="info-list">
                  <div className="info-item">
                    <strong>{__("Gateway:", "arraysubs")}</strong>
                    {data.gateway_info.title}
                  </div>

                  {data.gateway_info.payment_method && (
                    <>
                      <div className="info-item">
                        <strong>{__("Card on File:", "arraysubs")}</strong>
                        <span className="arraysubs-payment-method-display">
                          {data.gateway_info.payment_method.title}
                        </span>
                      </div>
                      {data.gateway_info.payment_method.expiry && (
                        <div className="info-item">
                          <strong>{__("Expires:", "arraysubs")}</strong>
                          <span
                            className={
                              data.gateway_info.payment_method.is_expired
                                ? "arraysubs-pm-expired"
                                : ""
                            }
                          >
                            {data.gateway_info.payment_method.expiry}
                            {data.gateway_info.payment_method.is_expired && (
                              <span className="arraysubs-pm-expired-badge">
                                {__("Expired", "arraysubs")}
                              </span>
                            )}
                          </span>
                        </div>
                      )}
                    </>
                  )}

                  {data.gateway_info.customer_id && (
                    <div className="info-item">
                      <strong>{__("Customer ID:", "arraysubs")}</strong>
                      <code>{data.gateway_info.customer_id}</code>
                    </div>
                  )}

                  {data.gateway_info.last_transaction_id && (
                    <div className="info-item">
                      <strong>{__("Last Transaction:", "arraysubs")}</strong>
                      <code>{data.gateway_info.last_transaction_id}</code>
                    </div>
                  )}

                  {(canResyncGateway || data.gateway_info.can_detach) && (
                    <div className="info-item arraysubs-gateway-card__actions">
                      {canResyncGateway && (
                        <SpinnerButton
                          type="button"
                          className="button arraysubs-btn--small"
                          onClick={handleGatewaySync}
                          loading={syncProcessing}
                          loadingText={__("Syncing…", "arraysubs")}
                          iconSize={14}
                          title={__(
                            "Pull the latest subscription state from the gateway and reconcile any missed webhook events.",
                            "arraysubs",
                          )}
                        >
                          <RefreshCw size={14} style={{ marginRight: "4px" }} />
                          {__("Resync from Gateway", "arraysubs")}
                        </SpinnerButton>
                      )}
                      {data.gateway_info.can_detach && (
                        <SpinnerButton
                          type="button"
                          className="button arraysubs-btn--danger arraysubs-btn--small"
                          onClick={handleDetachGateway}
                          loading={detachProcessing}
                          loadingText={__("Detaching…", "arraysubs")}
                          iconSize={14}
                        >
                          <Unlink size={14} style={{ marginRight: "4px" }} />
                          {__("Detach Gateway", "arraysubs")}
                        </SpinnerButton>
                      )}
                    </div>
                  )}
                </div>
              </div>
            </div>
          )}

          {/* Billing Address */}
          <div className="detail-card">
            <div className="detail-card__header">
              <MapPin size={20} />
              <h3>{__("Billing Address", "arraysubs")}</h3>
            </div>
            <div className="detail-card__body">
              {data.billing_address &&
              Object.keys(data.billing_address).length > 0 ? (
                <address>
                  {data.billing_address.first_name}{" "}
                  {data.billing_address.last_name}
                  <br />
                  {data.billing_address.company && (
                    <>
                      {data.billing_address.company}
                      <br />
                    </>
                  )}
                  {data.billing_address.address_1}
                  <br />
                  {data.billing_address.address_2 && (
                    <>
                      {data.billing_address.address_2}
                      <br />
                    </>
                  )}
                  {data.billing_address.city}, {data.billing_address.state}{" "}
                  {data.billing_address.postcode}
                  <br />
                  {data.billing_address.country}
                  <br />
                  <br />
                  <strong>{__("Email:", "arraysubs")}</strong>{" "}
                  {data.billing_address.email}
                  <br />
                  <strong>{__("Phone:", "arraysubs")}</strong>{" "}
                  {data.billing_address.phone}
                </address>
              ) : (
                <p>{__("No billing address on file", "arraysubs")}</p>
              )}
            </div>
          </div>

          {/* Shipping Address */}
          <div className="detail-card">
            <div className="detail-card__header">
              <MapPin size={20} />
              <h3>{__("Shipping Address", "arraysubs")}</h3>
            </div>
            <div className="detail-card__body">
              {data.shipping_address &&
              Object.keys(data.shipping_address).length > 0 ? (
                <address>
                  {data.shipping_address.first_name}{" "}
                  {data.shipping_address.last_name}
                  <br />
                  {data.shipping_address.company && (
                    <>
                      {data.shipping_address.company}
                      <br />
                    </>
                  )}
                  {data.shipping_address.address_1}
                  <br />
                  {data.shipping_address.address_2 && (
                    <>
                      {data.shipping_address.address_2}
                      <br />
                    </>
                  )}
                  {data.shipping_address.city}, {data.shipping_address.state}{" "}
                  {data.shipping_address.postcode}
                  <br />
                  {data.shipping_address.country}
                </address>
              ) : (
                <p>{__("No shipping address on file", "arraysubs")}</p>
              )}
            </div>
          </div>

          {/* Subscription Shipping */}
          {data.shipping?.needs_shipping && (
            <div className="detail-card">
              <div className="detail-card__header">
                <Package size={20} />
                <h3>{__("Subscription Shipping", "arraysubs")}</h3>
              </div>
              <div className="detail-card__body">
                <dl className="arraysubs-detail-list">
                  <dt>{__("Shipping Type", "arraysubs")}</dt>
                  <dd>
                    <span
                      className={`shipping-type-badge shipping-type-badge--${data.shipping.shipping_type}`}
                    >
                      {data.shipping.shipping_type === "one-time"
                        ? __("One-time (first order only)", "arraysubs")
                        : __("Recurring (every renewal)", "arraysubs")}
                    </span>
                  </dd>
                  <dt>{__("Shipping Method", "arraysubs")}</dt>
                  <dd>
                    {data.shipping.shipping_method_title ||
                      __("Not set", "arraysubs")}
                  </dd>
                  <dt>{__("Initial Shipping", "arraysubs")}</dt>
                  <dd>{formatCurrency(data.shipping.shipping_total)}</dd>
                  {data.shipping.shipping_type === "recurring" && (
                    <>
                      <dt>{__("Renewal Shipping", "arraysubs")}</dt>
                      <dd>
                        {formatCurrency(data.shipping.renewal_shipping_total)}
                      </dd>
                    </>
                  )}
                  <dt>{__("Initial Shipping Paid", "arraysubs")}</dt>
                  <dd>
                    {data.shipping.initial_shipping_paid
                      ? __("Yes", "arraysubs")
                      : __("No", "arraysubs")}
                  </dd>
                </dl>
              </div>
            </div>
          )}

          {/* Orders History */}
          <div className="detail-card detail-card--full">
            <div className="detail-card__header">
              <History size={20} />
              <h3>{__("Order History", "arraysubs")}</h3>
              {data.total_refunded > 0 && (
                <span className="refund-badge">
                  {__("Total Refunded:", "arraysubs")}{" "}
                  {data.formatted_total_refunded}
                </span>
              )}
            </div>
            <div className="detail-card__body">
              {data.orders && data.orders.length > 0 ? (
                <table className="wp-list-table widefat fixed striped">
                  <thead>
                    <tr>
                      <th>{__("Order", "arraysubs")}</th>
                      <th>{__("Date", "arraysubs")}</th>
                      <th>{__("Status", "arraysubs")}</th>
                      <th>{__("Total", "arraysubs")}</th>
                      <th>{__("Refunded", "arraysubs")}</th>
                      <th>{__("Type", "arraysubs")}</th>
                      <th>{__("Actions", "arraysubs")}</th>
                    </tr>
                  </thead>
                  <tbody>
                    {data.orders.map((order) => (
                      <React.Fragment key={order.id}>
                        <tr
                          className={
                            order.is_fully_refunded ? "order-row--refunded" : ""
                          }
                        >
                          <td>#{order.id}</td>
                          <td>{formatDate(order.date_display, order.date)}</td>
                          <td>{order.status}</td>
                          <td>{order.formatted_total}</td>
                          <td>
                            {order.total_refunded > 0 ? (
                              <span
                                className={
                                  order.is_fully_refunded
                                    ? "refund-amount refund-amount--full"
                                    : "refund-amount"
                                }
                              >
                                -{order.formatted_refunded}
                              </span>
                            ) : (
                              "-"
                            )}
                          </td>
                          <td>
                            {order.is_renewal
                              ? __("Renewal", "arraysubs")
                              : __("Initial", "arraysubs")}
                          </td>
                          <td>
                            <a
                              href={`${env.wpAdminUrl}post.php?post=${order.id}&action=edit`}
                              target="_blank"
                              rel="noopener noreferrer"
                              className="button button-small"
                            >
                              {__("View Order", "arraysubs")}
                            </a>
                          </td>
                        </tr>
                        {/* Show individual refunds */}
                        {order.refunds &&
                          order.refunds.length > 0 &&
                          order.refunds.map((refund) => (
                            <tr
                              key={`refund-${refund.id}`}
                              className="refund-row"
                            >
                              <td colSpan={2}>
                                └ {__("Refund", "arraysubs")} #{refund.id}
                              </td>
                              <td>
                                {formatDate(refund.date_display, refund.date)}
                              </td>
                              <td colSpan={2}>-{refund.formatted_amount}</td>
                              <td colSpan={2}>
                                {refund.reason ||
                                  __("No reason provided", "arraysubs")}
                              </td>
                            </tr>
                          ))}
                      </React.Fragment>
                    ))}
                  </tbody>
                </table>
              ) : (
                <p>{__("No orders found", "arraysubs")}</p>
              )}
            </div>
          </div>

          {/* Payment Timeline */}
          <div className="detail-card">
            <div className="detail-card__header">
              <History size={20} />
              <h3>{__("Payment Timeline", "arraysubs")}</h3>
            </div>
            <div className="detail-card__body">
              <PaymentTimeline
                orders={data.orders || []}
                subscriptionId={parseInt(id)}
                apiBaseUrl={env.apiBaseUrl}
                nonce={env.nonce}
                compact
              />
            </div>
          </div>

          {/* Subscription Notes */}
          <div className="detail-card">
            <div className="detail-card__header">
              <FileText size={20} />
              <h3>{__("Subscription Notes", "arraysubs")}</h3>
            </div>
            <div className="detail-card__body">
              <NotesPanel subscriptionId={parseInt(id)} compact />
            </div>
          </div>
        </div>
      </div>

      <Modal
        isOpen={proratedModalOpen}
        onClose={handleCloseProratedRefund}
        title={__("Prorated Refund", "arraysubs")}
        size="md"
        closeOnBackdrop={!proratedProcessing}
        closeOnEsc={!proratedProcessing}
        showCloseButton={!proratedProcessing}
      >
        <div className="arraysubs-prorated-refund-modal">
          {proratedPreviewLoading ? (
            <div className="arraysubs-loading">
              {__("Calculating prorated refund...", "arraysubs")}
            </div>
          ) : proratedError ? (
            <div className="arraysubs-prorated-refund-modal__notice arraysubs-prorated-refund-modal__notice--error">
              {proratedError}
            </div>
          ) : (
            <>
              <div className="arraysubs-prorated-refund-modal__summary">
                <div>
                  <span>{__("Days in Cycle", "arraysubs")}</span>
                  <strong>{proratedPreview?.cycle_days || 0}</strong>
                </div>
                <div>
                  <span>{__("Unused Days", "arraysubs")}</span>
                  <strong>
                    {formatDayCount(proratedPreview?.days_unused || 0)}
                  </strong>
                </div>
                <div>
                  <span>{__("Daily Rate", "arraysubs")}</span>
                  <strong>{formatCurrency(proratedPreview?.daily_rate || 0)}</strong>
                </div>
              </div>

              <div className="arraysubs-prorated-refund-modal__field">
                <label htmlFor="arraysubs-prorated-refund-amount">
                  {__("Refund Amount", "arraysubs")}
                </label>
                <input
                  id="arraysubs-prorated-refund-amount"
                  type="number"
                  value={getProratedPreviewAmount()}
                  readOnly
                />
              </div>

              <div className="arraysubs-prorated-refund-modal__field">
                <label htmlFor="arraysubs-prorated-refund-reason">
                  {__("Reason", "arraysubs")}
                </label>
                <textarea
                  id="arraysubs-prorated-refund-reason"
                  value={proratedReason}
                  onChange={(event) => setProratedReason(event.target.value)}
                  rows={3}
                  disabled={proratedProcessing}
                />
              </div>

              <label className="arraysubs-prorated-refund-modal__checkbox">
                <input
                  type="checkbox"
                  checked={proratedCancelAfter}
                  onChange={(event) =>
                    setProratedCancelAfter(event.target.checked)
                  }
                  disabled={proratedProcessing}
                />
                <span>{__("Cancel after refund", "arraysubs")}</span>
              </label>
            </>
          )}

          <div className="arraysubs-prorated-refund-modal__actions">
            <button
              type="button"
              className="button"
              onClick={handleCloseProratedRefund}
              disabled={proratedProcessing}
            >
              {__("Close", "arraysubs")}
            </button>
            <SpinnerButton
              type="button"
              className="button button-primary"
              onClick={handleProcessProratedRefund}
              loading={proratedProcessing}
              loadingText={__("Processing…", "arraysubs")}
              disabled={
                proratedPreviewLoading || !!proratedError || !proratedPreview
              }
            >
              {__("Process Refund", "arraysubs")}
            </SpinnerButton>
          </div>
        </div>
      </Modal>

      {/* Cancel Modal */}
      <CancelModal
        isOpen={cancelModalOpen}
        onClose={() => setCancelModalOpen(false)}
        onConfirm={handleCancelSubscription}
        subscription={{
          id: data?.id,
          next_payment_date: data?.next_payment_date,
          next_payment_date_display: data?.next_payment_date_display,
        }}
      />

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

export default SubscriptionDetail;
