import React, { useState, useEffect, useCallback } from "react";
import { __ } from "@wordpress/i18n";
import { decodeEntities } from "@wordpress/html-entities";
import { buildUrl } from "@libs/url";
import { ChevronLeft, ChevronRight } from "lucide-react";

const EVENT_LABELS = {
  cancelled: __("Cancelled", "arraysubs"),
  scheduled_cancel: __("Scheduled Cancel", "arraysubs"),
  cancel_undone: __("Cancel Undone", "arraysubs"),
  offer_shown: __("Offer Shown", "arraysubs"),
  offer_accepted: __("Offer Accepted", "arraysubs"),
  offer_declined: __("Offer Declined", "arraysubs"),
};

const EVENT_COLORS = {
  cancelled: "#e74c3c",
  scheduled_cancel: "#e67e22",
  cancel_undone: "#27ae60",
  offer_shown: "#3498db",
  offer_accepted: "#2ecc71",
  offer_declined: "#95a5a6",
};

const ActivityLogs = ({
  startDate,
  endDate,
  productIds,
  apiBaseUrl,
  nonce,
  currency,
}) => {
  const [logs, setLogs] = useState([]);
  const [loading, setLoading] = useState(true);
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(0);
  const [eventFilter, setEventFilter] = useState("");
  const perPage = 15;

  const fetchLogs = useCallback(async () => {
    setLoading(true);

    try {
      const params = {
        start_date: startDate,
        end_date: endDate,
        page,
        per_page: perPage,
      };

      if (productIds.length > 0) {
        params.product_ids = productIds.join(",");
      }

      if (eventFilter) {
        params.event_type = eventFilter;
      }

      const url = buildUrl(
        `${apiBaseUrl}arraysubs/v1/retention-analytics/logs`,
        params,
      );

      const response = await fetch(url, {
        headers: { "X-WP-Nonce": nonce },
      });

      if (!response.ok) {
        throw new Error("Failed to fetch logs");
      }

      const result = await response.json();
      const data = result.content || result;

      setLogs(data.items || []);
      setTotal(parseInt(data.total || 0, 10));
    } catch (error) {
      console.error("Activity logs fetch error:", error);
      setLogs([]);
      setTotal(0);
    } finally {
      setLoading(false);
    }
  }, [startDate, endDate, productIds, page, eventFilter, apiBaseUrl, nonce]);

  useEffect(() => {
    fetchLogs();
  }, [fetchLogs]);

  useEffect(() => {
    setPage(1);
  }, [startDate, endDate, productIds, eventFilter]);

  const totalPages = Math.ceil(total / perPage);

  const formatAmount = (amount) => {
    if (!amount) return "";
    const num = parseFloat(amount);
    const currencySymbol = decodeEntities(currency || "$") || "$";

    return `${currencySymbol}${num.toLocaleString(undefined, {
      minimumFractionDigits: 2,
      maximumFractionDigits: 2,
    })}`;
  };

  return (
    <div className="arraysubs-retention-logs">
      <div className="arraysubs-retention-logs__header">
        <h3 className="arraysubs-retention-logs__title">
          {__("Activity Log", "arraysubs")}
        </h3>
        <div className="arraysubs-retention-logs__event-filter">
          <select
            className="arraysubs-retention-logs__event-select"
            value={eventFilter}
            onChange={(e) => setEventFilter(e.target.value)}
          >
            <option value="">{__("All Events", "arraysubs")}</option>
            {Object.entries(EVENT_LABELS).map(([key, label]) => (
              <option key={key} value={key}>
                {label}
              </option>
            ))}
          </select>
        </div>
      </div>

      <div className="arraysubs-retention-logs__table-wrapper">
        <table className="arraysubs-retention-logs__table">
          <thead>
            <tr>
              <th>{__("Date", "arraysubs")}</th>
              <th>{__("Event", "arraysubs")}</th>
              <th>{__("Customer", "arraysubs")}</th>
              <th>{__("Product", "arraysubs")}</th>
              <th>{__("Reason", "arraysubs")}</th>
              <th>{__("Offer", "arraysubs")}</th>
              <th>{__("Amount", "arraysubs")}</th>
              <th>{__("Sub. Age", "arraysubs")}</th>
            </tr>
          </thead>
          <tbody>
            {loading ? (
              Array.from({ length: 5 }).map((_, i) => (
                <tr
                  key={`skeleton-${i}`}
                  className="arraysubs-retention-logs__row--loading"
                >
                  {Array.from({ length: 8 }).map((_, j) => (
                    <td key={`skel-${i}-${j}`}>
                      <div className="arraysubs-retention-logs__skeleton-cell" />
                    </td>
                  ))}
                </tr>
              ))
            ) : logs.length === 0 ? (
              <tr>
                <td colSpan="8" className="arraysubs-retention-logs__empty">
                  {__("No activity logs found for this period.", "arraysubs")}
                </td>
              </tr>
            ) : (
              logs.map((log) => (
                <tr key={log.id} className="arraysubs-retention-logs__row">
                  <td className="arraysubs-retention-logs__cell--date">
                    {log.date || log.created_at || "—"}
                  </td>
                  <td>
                    <span
                      className="arraysubs-retention-logs__badge"
                      style={{
                        backgroundColor: EVENT_COLORS[log.event_type] || "#666",
                      }}
                    >
                      {EVENT_LABELS[log.event_type] || log.event_type}
                    </span>
                  </td>
                  <td>{log.customer_name || `#${log.customer_id}`}</td>
                  <td>
                    {log.product_name ||
                      (log.product_id ? `#${log.product_id}` : "—")}
                  </td>
                  <td>{log.reason || "—"}</td>
                  <td>{log.offer_type || "—"}</td>
                  <td>
                    {log.recurring_amount
                      ? formatAmount(log.recurring_amount)
                      : "—"}
                  </td>
                  <td>
                    {log.subscription_age ? `${log.subscription_age}d` : "—"}
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>

      {totalPages > 1 && (
        <div className="arraysubs-retention-logs__pagination">
          <span className="arraysubs-retention-logs__pagination-info">
            {__("Page", "arraysubs")} {page} {__("of", "arraysubs")}{" "}
            {totalPages} ({total} {__("total", "arraysubs")})
          </span>
          <div className="arraysubs-retention-logs__pagination-buttons">
            <button
              type="button"
              className="arraysubs-retention-logs__pagination-btn"
              disabled={page <= 1}
              onClick={() => setPage((p) => Math.max(1, p - 1))}
            >
              <ChevronLeft size={16} />
              {__("Previous", "arraysubs")}
            </button>
            <button
              type="button"
              className="arraysubs-retention-logs__pagination-btn"
              disabled={page >= totalPages}
              onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
            >
              {__("Next", "arraysubs")}
              <ChevronRight size={16} />
            </button>
          </div>
        </div>
      )}
    </div>
  );
};

export default ActivityLogs;
