import React, { useState, useEffect } from "react";
import { __ } from "@wordpress/i18n";
import {
  CheckCircle,
  XCircle,
  AlertCircle,
  Clock,
  RefreshCw,
  Pause,
  Play,
  Ban,
  FileText,
  CreditCard,
  ChevronDown,
  ChevronUp,
} from "lucide-react";
import { formatDateTimeForSite, parseUtcDateTime } from "@/libs/dateTime";
import { buildRestUrl } from "@/libs/url";
import "./payment-timeline.scss";

/**
 * Payment Timeline Component
 *
 * Displays a chronological timeline of subscription events including:
 * - Payment successes/failures
 * - Status changes
 * - Manual actions (skip, pause, etc.)
 * - System notes
 *
 * @param {number} subscriptionId - The subscription ID
 * @param {array} orders - Array of order objects from subscription data
 * @param {array} notes - Array of subscription notes (optional, fetched if not provided)
 * @param {string} apiBaseUrl - REST API base URL
 * @param {string} nonce - WP nonce for API calls
 */
const PaymentTimeline = ({
  subscriptionId,
  orders = [],
  notes: propNotes = null,
  apiBaseUrl,
  nonce,
  compact = false,
}) => {
  const [notes, setNotes] = useState(propNotes || []);
  const [loading, setLoading] = useState(!propNotes);
  const [expanded, setExpanded] = useState(true);
  const [showAll, setShowAll] = useState(false);

  // Fetch notes if not provided
  useEffect(() => {
    if (!propNotes && subscriptionId) {
      fetchNotes();
    }
  }, [subscriptionId, propNotes]);

  const fetchNotes = async () => {
    try {
      const response = await fetch(
        buildRestUrl(
          apiBaseUrl,
          `arraysubs/v1/subscriptions/${subscriptionId}/notes`,
        ),
        {
          headers: { "X-WP-Nonce": nonce },
        },
      );

      if (response.ok) {
        const result = await response.json();
        setNotes(result.content?.notes || result.content || []);
      }
    } catch (error) {
      console.error("Failed to fetch notes:", error);
    } finally {
      setLoading(false);
    }
  };

  // Combine orders and notes into timeline events
  const buildTimelineEvents = () => {
    const events = [];

    // Add order events
    orders.forEach((order) => {
      const isSuccess = ["completed", "processing"].includes(order.status);
      const isFailed = ["failed", "cancelled"].includes(order.status);
      const isPending = ["pending", "on-hold"].includes(order.status);

      events.push({
        id: `order-${order.id}`,
        type: "payment",
        status: isSuccess ? "success" : isFailed ? "failed" : "pending",
        title: order.is_renewal
          ? __("Renewal Payment", "arraysubs")
          : __("Initial Payment", "arraysubs"),
        description: `${__("Order", "arraysubs")} #${order.id} - ${
          order.formatted_total
        }`,
        dateTimestamp:
          order.date_timestamp ||
          Math.floor((parseUtcDateTime(order.date)?.getTime() || 0) / 1000),
        displayDate: order.date_display || formatDateTimeForSite(order.date),
        meta: {
          orderId: order.id,
          orderStatus: order.status,
          total: order.formatted_total,
        },
      });
    });

    // Add note events (filter for system notes that indicate events)
    notes.forEach((note) => {
      const eventType = detectEventType(note);

      events.push({
        id: `note-${note.id}`,
        type: eventType.type,
        status: eventType.status,
        title: eventType.title,
        description: note.content,
        dateTimestamp:
          note.date_timestamp ||
          Math.floor(
            (parseUtcDateTime(note.date_gmt || note.date)?.getTime() || 0) /
              1000,
          ),
        displayDate:
          note.date_display ||
          formatDateTimeForSite(note.date_gmt || note.date),
        meta: {
          noteType: note.note_type,
          eventType: note.event_type,
          addedBy: note.author_name,
        },
      });
    });

    // Sort by date (newest first)
    events.sort((a, b) => (b.dateTimestamp || 0) - (a.dateTimestamp || 0));

    return events;
  };

  // Detect event type from note metadata, falling back to legacy note content.
  const detectEventType = (note) => {
    const structuredEventType = getStructuredEventType(note.event_type);

    if (structuredEventType) {
      return structuredEventType;
    }

    const lowerContent = (note.content || "").toLowerCase();

    // Status changes
    if (
      lowerContent.includes("status changed") ||
      lowerContent.includes("activated")
    ) {
      return {
        type: "status_change",
        status: "info",
        title: __("Status Change", "arraysubs"),
      };
    }
    if (lowerContent.includes("cancelled")) {
      return {
        type: "status_change",
        status: "error",
        title: __("Cancelled", "arraysubs"),
      };
    }
    if (lowerContent.includes("on hold") || lowerContent.includes("on-hold")) {
      return {
        type: "status_change",
        status: "warning",
        title: __("Put On Hold", "arraysubs"),
      };
    }
    if (lowerContent.includes("expired")) {
      return {
        type: "status_change",
        status: "error",
        title: __("Expired", "arraysubs"),
      };
    }

    // Payment related
    if (lowerContent.includes("payment") && lowerContent.includes("failed")) {
      return {
        type: "payment",
        status: "failed",
        title: __("Payment Failed", "arraysubs"),
      };
    }
    if (
      lowerContent.includes("payment") &&
      (lowerContent.includes("received") || lowerContent.includes("completed"))
    ) {
      return {
        type: "payment",
        status: "success",
        title: __("Payment Received", "arraysubs"),
      };
    }

    // Renewal invoice creation — note text includes "awaiting payment"
    // or "invoice created" or "generated for payment due". This is a
    // pending state, NOT a successful payment. The order itself drives
    // the success/failed signal via the order-level event added above.
    if (
      lowerContent.includes("renewal invoice") ||
      lowerContent.includes("awaiting payment") ||
      lowerContent.includes("generated for payment due")
    ) {
      return {
        type: "renewal",
        status: "pending",
        title: __("Renewal Invoice Created", "arraysubs"),
      };
    }

    // Renewal payment success — explicit completion notes only.
    if (
      lowerContent.includes("renewal") &&
      (lowerContent.includes("payment received") ||
        lowerContent.includes("payment successful") ||
        lowerContent.includes("payment completed"))
    ) {
      return {
        type: "renewal",
        status: "success",
        title: __("Renewal Payment Successful", "arraysubs"),
      };
    }
    if (lowerContent.includes("skipped")) {
      return {
        type: "action",
        status: "info",
        title: __("Payment Skipped", "arraysubs"),
      };
    }

    // Default to note
    return {
      type: "note",
      status: "info",
      title: __("Note", "arraysubs"),
    };
  };

  const getStructuredEventType = (eventType) => {
    switch (eventType) {
      case "renewal_invoice_created":
        return {
          type: "renewal",
          status: "pending",
          title: __("Renewal Invoice Created", "arraysubs"),
        };
      case "renewal_payment_succeeded":
        return {
          type: "renewal",
          status: "success",
          title: __("Renewal Payment Successful", "arraysubs"),
        };
      case "renewal_payment_failed":
        return {
          type: "renewal",
          status: "failed",
          title: __("Renewal Payment Failed", "arraysubs"),
        };
      case "retry_scheduled":
        return {
          type: "renewal",
          status: "pending",
          title: __("Payment Retry Scheduled", "arraysubs"),
        };
      case "payment_succeeded":
        return {
          type: "payment",
          status: "success",
          title: __("Payment Received", "arraysubs"),
        };
      case "payment_failed":
        return {
          type: "payment",
          status: "failed",
          title: __("Payment Failed", "arraysubs"),
        };
      default:
        return null;
    }
  };

  // Get icon for event type
  const getEventIcon = (event) => {
    const iconProps = { size: 16 };

    switch (event.type) {
      case "payment":
        if (event.status === "success") return <CheckCircle {...iconProps} />;
        if (event.status === "failed") return <XCircle {...iconProps} />;
        return <Clock {...iconProps} />;

      case "status_change":
        if (event.status === "error") return <Ban {...iconProps} />;
        if (event.status === "warning") return <Pause {...iconProps} />;
        return <Play {...iconProps} />;

      case "renewal":
        return <RefreshCw {...iconProps} />;

      case "action":
        return <AlertCircle {...iconProps} />;

      default:
        return <FileText {...iconProps} />;
    }
  };

  // Get status class for styling
  const getStatusClass = (event) => {
    switch (event.status) {
      case "success":
        return "timeline-event--success";
      case "failed":
      case "error":
        return "timeline-event--error";
      case "warning":
        return "timeline-event--warning";
      case "pending":
        return "timeline-event--pending";
      default:
        return "timeline-event--info";
    }
  };

  const events = buildTimelineEvents();
  const displayEvents = showAll ? events : events.slice(0, 5);
  const hasMore = events.length > 5;

  if (loading) {
    return (
      <div className="arraysubs-payment-timeline">
        <div className="timeline-loading">
          {__("Loading timeline...", "arraysubs")}
        </div>
      </div>
    );
  }

  return (
    <div
      className={`arraysubs-payment-timeline${
        compact ? " arraysubs-payment-timeline--compact" : ""
      }`}
    >
      {!compact && (
        <div
          className="timeline-header"
          onClick={() => setExpanded(!expanded)}
          role="button"
          tabIndex={0}
          onKeyDown={(e) => e.key === "Enter" && setExpanded(!expanded)}
        >
          <div className="timeline-header__title">
            <CreditCard size={20} />
            <h3>{__("Payment & Activity Timeline", "arraysubs")}</h3>
            <span className="timeline-header__count">({events.length})</span>
          </div>
          <button type="button" className="timeline-header__toggle">
            {expanded ? <ChevronUp size={20} /> : <ChevronDown size={20} />}
          </button>
        </div>
      )}

      {(compact || expanded) && (
        <div className="timeline-content">
          {events.length === 0 ? (
            <p className="timeline-empty">
              {__("No activity recorded yet.", "arraysubs")}
            </p>
          ) : (
            <>
              <div className="timeline-events">
                {displayEvents.map((event) => (
                  <div
                    key={event.id}
                    className={`timeline-event ${getStatusClass(event)}`}
                  >
                    <div className="timeline-event__marker">
                      <div className="timeline-event__icon">
                        {getEventIcon(event)}
                      </div>
                      <div className="timeline-event__line" />
                    </div>
                    <div className="timeline-event__content">
                      <div className="timeline-event__header">
                        <span className="timeline-event__title">
                          {event.title}
                        </span>
                        <span className="timeline-event__date">
                          {event.displayDate}
                        </span>
                      </div>
                      <p
                        className="timeline-event__description"
                        dangerouslySetInnerHTML={{
                          __html: event.description,
                        }}
                      />
                      {event.meta?.orderId && (
                        <a
                          href={`${window.arraySubs?.env?.wpAdminUrl}post.php?post=${event.meta.orderId}&action=edit`}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="timeline-event__link"
                        >
                          {__("View Order", "arraysubs")} →
                        </a>
                      )}
                    </div>
                  </div>
                ))}
              </div>

              {hasMore && (
                <button
                  type="button"
                  className="timeline-show-more"
                  onClick={() => setShowAll(!showAll)}
                >
                  {showAll
                    ? __("Show Less", "arraysubs")
                    : `${__("Show All", "arraysubs")} (${events.length})`}
                </button>
              )}
            </>
          )}
        </div>
      )}
    </div>
  );
};

export default PaymentTimeline;
