import React from "react";
import { __ } from "@wordpress/i18n";
import DefaultPageLayout from "@/components/DefaultPageLayout";
import { buildUrl } from "@libs/url";
import {
  BarChart3,
  TrendingUp,
  ShoppingCart,
  Package,
  Users,
  Wallet,
  Activity,
  FileText,
  Crown,
  LayoutDashboard,
  ArrowUpRight,
  Layers,
  PieChart,
  HeartHandshake,
  ClipboardList,
  Receipt,
  BadgeDollarSign,
  GitCompare,
  CreditCard,
  Filter,
  UserSearch,
  ListOrdered,
  Tag,
  Box,
} from "lucide-react";

const { env } = window.arraySubs || {};

const hasLoadedFeature = (fragment) => {
  const classes = window.arraySubs?.liveBootClasses || [];
  return classes.some((cls) => cls.includes(fragment));
};

const hasAnalytics = hasLoadedFeature("Analytics");
const hasStoreCredit = hasLoadedFeature("StoreCredit");
const hasMemberInsight = hasLoadedFeature("MemberInsight");
const hasAudits = hasLoadedFeature("Audits");
const hasAutoPayments = hasLoadedFeature("AutomaticPayments");

/**
 * Build a WooCommerce admin URL for analytics pages.
 * Uses admin.php?page=wc-admin&path=...
 */
const wcAdminUrl = (path, params = {}) => {
  return buildUrl(`${env?.wpAdminUrl || ""}admin.php`, {
    page: "wc-admin",
    path,
    ...params,
  });
};

/**
 * Build an ArraySubs admin SPA URL (hash-based routing).
 */
const arraySubsUrl = (hashPath) => {
  return `${env?.wpAdminUrl || ""}admin.php?page=arraysubs#${hashPath}`;
};

const REPORT_SECTIONS = [
  {
    id: "subscription-performance",
    title: __("Subscription Performance", "arraysubs"),
    description: __(
      "Key business metrics, trends, and product leaderboards on the WooCommerce Analytics Overview page.",
      "arraysubs",
    ),
    icon: LayoutDashboard,
    isPro: true,
    available: hasAnalytics,
    reports: [
      {
        title: __("Performance Dashboard", "arraysubs"),
        description: __(
          "10 KPI cards including MRR, active subscriptions, churn rate, trial conversions, ARPU, and more with period comparison.",
          "arraysubs",
        ),
        icon: BarChart3,
        url: wcAdminUrl("/analytics/overview"),
        isPro: true,
      },
      {
        title: __("MRR Trend Chart", "arraysubs"),
        description: __(
          "Monthly Recurring Revenue over time with interval selection.",
          "arraysubs",
        ),
        icon: TrendingUp,
        url: wcAdminUrl("/analytics/overview"),
        isPro: true,
      },
      {
        title: __("Net Subscription Growth Chart", "arraysubs"),
        description: __(
          "New subscriptions minus cancellations per interval.",
          "arraysubs",
        ),
        icon: TrendingUp,
        url: wcAdminUrl("/analytics/overview"),
        isPro: true,
      },
      {
        title: __("Churn Rate Chart", "arraysubs"),
        description: __("Cancellation rate trend over time.", "arraysubs"),
        icon: Activity,
        url: wcAdminUrl("/analytics/overview"),
        isPro: true,
      },
      {
        title: __("Renewal Revenue Chart", "arraysubs"),
        description: __(
          "Total renewal order revenue per interval.",
          "arraysubs",
        ),
        icon: BadgeDollarSign,
        url: wcAdminUrl("/analytics/overview"),
        isPro: true,
      },
      {
        title: __("Trial Conversion Rate Chart", "arraysubs"),
        description: __(
          "Trial-to-paid conversion rate per interval.",
          "arraysubs",
        ),
        icon: GitCompare,
        url: wcAdminUrl("/analytics/overview"),
        isPro: true,
      },
      {
        title: __("Active Subscriptions Chart", "arraysubs"),
        description: __(
          "Active subscription count trend over time.",
          "arraysubs",
        ),
        icon: Users,
        url: wcAdminUrl("/analytics/overview"),
        isPro: true,
      },
    ],
  },
  {
    id: "leaderboards",
    title: __("Leaderboards", "arraysubs"),
    description: __(
      "Ranked tables on the WooCommerce Analytics Overview page showing top products, customers, and churn data.",
      "arraysubs",
    ),
    icon: Crown,
    isPro: true,
    available: hasAnalytics,
    reports: [
      {
        title: __("Top Subscription Products — Active", "arraysubs"),
        description: __(
          "Products ranked by active subscription count and MRR contribution.",
          "arraysubs",
        ),
        icon: Package,
        url: wcAdminUrl("/analytics/overview"),
        isPro: true,
      },
      {
        title: __("Top Subscription Products — Revenue", "arraysubs"),
        description: __(
          "Products ranked by total order revenue and order count.",
          "arraysubs",
        ),
        icon: BadgeDollarSign,
        url: wcAdminUrl("/analytics/overview"),
        isPro: true,
      },
      {
        title: __("Top Subscribers — Lifetime Value", "arraysubs"),
        description: __(
          "Customers ranked by active subscriptions and total spending.",
          "arraysubs",
        ),
        icon: Users,
        url: wcAdminUrl("/analytics/overview"),
        isPro: true,
      },
      {
        title: __("Top Cancellation Reasons", "arraysubs"),
        description: __(
          "Most common cancellation reasons with count and percentage.",
          "arraysubs",
        ),
        icon: ClipboardList,
        url: wcAdminUrl("/analytics/overview"),
        isPro: true,
      },
      {
        title: __("Highest Churn Products", "arraysubs"),
        description: __(
          "Products ranked by cancellation volume and churn rate.",
          "arraysubs",
        ),
        icon: Activity,
        url: wcAdminUrl("/analytics/overview"),
        isPro: true,
      },
    ],
  },
  {
    id: "retention-analytics",
    title: __("Retention Analytics", "arraysubs"),
    description: __(
      "Cancellation and retention flow analytics under WooCommerce Analytics.",
      "arraysubs",
    ),
    icon: HeartHandshake,
    isPro: false,
    available: true,
    reports: [
      {
        title: __("Retention Summary", "arraysubs"),
        description: __(
          "Cancellations, average age at cancel, average payments before cancel, saved revenue, and offer acceptance rate.",
          "arraysubs",
        ),
        icon: PieChart,
        url: wcAdminUrl("/analytics/arraysubs-retention"),
        isPro: false,
      },
      {
        title: __("Churn Reasons Breakdown", "arraysubs"),
        description: __(
          "Visual chart of cancellation reasons with drill-down.",
          "arraysubs",
        ),
        icon: ClipboardList,
        url: wcAdminUrl("/analytics/arraysubs-retention"),
        isPro: false,
      },
      {
        title: __("Retention Offer Performance", "arraysubs"),
        description: __(
          "Offers shown vs accepted by type (Discount, Pause, Downgrade, Contact Support).",
          "arraysubs",
        ),
        icon: HeartHandshake,
        url: wcAdminUrl("/analytics/arraysubs-retention"),
        isPro: false,
      },
      {
        title: __("Retention Trend Chart", "arraysubs"),
        description: __(
          "Daily cancellation and retention activity over the selected date range.",
          "arraysubs",
        ),
        icon: TrendingUp,
        url: wcAdminUrl("/analytics/arraysubs-retention"),
        isPro: false,
      },
      {
        title: __("Activity Logs", "arraysubs"),
        description: __(
          "Detailed event log — cancelled, scheduled cancel, cancel undone, offer shown, offered accepted, offer declined.",
          "arraysubs",
        ),
        icon: FileText,
        url: wcAdminUrl("/analytics/arraysubs-retention"),
        isPro: false,
      },
      {
        title: __("Product-Level Retention", "arraysubs"),
        description: __(
          "Filter all retention analytics by specific subscription product.",
          "arraysubs",
        ),
        icon: Filter,
        url: wcAdminUrl("/analytics/arraysubs-retention"),
        isPro: false,
      },
    ],
  },
  {
    id: "wc-orders",
    title: __("Orders Analytics", "arraysubs"),
    description: __(
      "Enhanced WooCommerce Orders report with subscription type classification, coupon tracking, and advanced filters.",
      "arraysubs",
    ),
    icon: ShoppingCart,
    isPro: true,
    available: hasAnalytics,
    reports: [
      {
        title: __("All Orders by Type", "arraysubs"),
        description: __(
          "Orders report with Type column showing Subs Purchase, Subs Renew, Subs Trial, Subs Upgrade, Credit Purchase, or Other.",
          "arraysubs",
        ),
        icon: ShoppingCart,
        url: wcAdminUrl("/analytics/orders"),
        isPro: true,
      },
      {
        title: __("Renewal Orders Only", "arraysubs"),
        description: __(
          "Filter to show only subscription renewal orders.",
          "arraysubs",
        ),
        icon: Receipt,
        url: wcAdminUrl("/analytics/orders", {
          filter: "advanced",
          arraysubs_type_is: "renewal",
        }),
        isPro: true,
      },
      {
        title: __("Initial Purchase Orders", "arraysubs"),
        description: __(
          "Filter to show only initial subscription purchase orders.",
          "arraysubs",
        ),
        icon: CreditCard,
        url: wcAdminUrl("/analytics/orders", {
          filter: "advanced",
          arraysubs_type_is: "new",
        }),
        isPro: true,
      },
      {
        title: __("Trial Orders", "arraysubs"),
        description: __(
          "Filter to show only subscription trial orders.",
          "arraysubs",
        ),
        icon: FileText,
        url: wcAdminUrl("/analytics/orders", {
          filter: "advanced",
          arraysubs_type_is: "trial",
        }),
        isPro: true,
      },
      {
        title: __("Plan Switch Orders", "arraysubs"),
        description: __(
          "Filter to show only plan switch (upgrade/downgrade) orders.",
          "arraysubs",
        ),
        icon: GitCompare,
        url: wcAdminUrl("/analytics/orders", {
          filter: "advanced",
          arraysubs_type_is: "switch",
        }),
        isPro: true,
      },
      {
        title: __("Credit Purchase Orders", "arraysubs"),
        description: __(
          "Filter to show only Store Credit purchase orders.",
          "arraysubs",
        ),
        icon: Wallet,
        url: wcAdminUrl("/analytics/orders", {
          filter: "advanced",
          arraysubs_type_is: "credit",
        }),
        isPro: true,
      },
    ],
  },
  {
    id: "wc-revenue",
    title: __("Revenue Analytics", "arraysubs"),
    description: __(
      "WooCommerce Revenue report extended with subscription-specific revenue breakdowns.",
      "arraysubs",
    ),
    icon: BadgeDollarSign,
    isPro: true,
    available: hasAnalytics,
    reports: [
      {
        title: __("Revenue Overview", "arraysubs"),
        description: __(
          "Standard revenue report with added Subs Renewal Amount, Subs Upgrade Amount, and Credit Purchase Amount cards.",
          "arraysubs",
        ),
        icon: TrendingUp,
        url: wcAdminUrl("/analytics/revenue"),
        isPro: true,
      },
      {
        title: __("Subscription Renewal Revenue", "arraysubs"),
        description: __(
          "Total revenue from renewal type orders across the selected period.",
          "arraysubs",
        ),
        icon: Receipt,
        url: wcAdminUrl("/analytics/revenue"),
        isPro: true,
      },
      {
        title: __("Subscription Upgrade Revenue", "arraysubs"),
        description: __(
          "Total revenue from plan switch orders across the selected period.",
          "arraysubs",
        ),
        icon: GitCompare,
        url: wcAdminUrl("/analytics/revenue"),
        isPro: true,
      },
    ],
  },
  {
    id: "wc-products",
    title: __("Products & Variations Analytics", "arraysubs"),
    description: __(
      "WooCommerce Products and Variations reports with subscription product filtering.",
      "arraysubs",
    ),
    icon: Package,
    isPro: true,
    available: hasAnalytics,
    reports: [
      {
        title: __("Subscription Products Report", "arraysubs"),
        description: __(
          "Products report filtered to show only subscription products.",
          "arraysubs",
        ),
        icon: Package,
        url: wcAdminUrl("/analytics/products"),
        isPro: true,
      },
      {
        title: __("Subscription Variations Report", "arraysubs"),
        description: __(
          "Variations report filtered to show only subscription product variations.",
          "arraysubs",
        ),
        icon: Layers,
        url: wcAdminUrl("/analytics/variations"),
        isPro: true,
      },
    ],
  },
  {
    id: "wc-customers",
    title: __("Customers Analytics", "arraysubs"),
    description: __(
      "WooCommerce Customers report with quick links to member detail profiles.",
      "arraysubs",
    ),
    icon: Users,
    isPro: true,
    available: hasAnalytics,
    reports: [
      {
        title: __("Customers Report with Member Links", "arraysubs"),
        description: __(
          "Standard WooCommerce Customers report with Member Details links to subscription profiles.",
          "arraysubs",
        ),
        icon: UserSearch,
        url: wcAdminUrl("/analytics/customers"),
        isPro: true,
      },
    ],
  },
  {
    id: "order-list",
    title: __("Order List Enhancements", "arraysubs"),
    description: __(
      "Enhanced WooCommerce Orders admin page with type columns, coupon columns, filters, and summary panel.",
      "arraysubs",
    ),
    icon: ListOrdered,
    isPro: true,
    available: hasAnalytics,
    reports: [
      {
        title: __("Order List — All Types", "arraysubs"),
        description: __(
          "Orders page with Type and Coupon columns, per-type count summary panel.",
          "arraysubs",
        ),
        icon: ListOrdered,
        url: buildUrl(`${env?.wpAdminUrl || ""}admin.php`, {
          page: "wc-orders",
        }),
        isPro: true,
      },
      {
        title: __("Filter by Order Type", "arraysubs"),
        description: __(
          "Use the Type dropdown to filter by Subs Purchase, Subs Renew, Subs Trial, Subs Upgrade, Credit Purchase, or Other.",
          "arraysubs",
        ),
        icon: Filter,
        url: buildUrl(`${env?.wpAdminUrl || ""}admin.php`, {
          page: "wc-orders",
        }),
        isPro: true,
      },
      {
        title: __("Filter by Coupon", "arraysubs"),
        description: __(
          "Use the Coupon dropdown to filter orders by specific coupon code usage.",
          "arraysubs",
        ),
        icon: Tag,
        url: buildUrl(`${env?.wpAdminUrl || ""}admin.php`, {
          page: "wc-orders",
        }),
        isPro: true,
      },
    ],
  },
  {
    id: "subscriptions",
    title: __("Subscriptions", "arraysubs"),
    description: __(
      "View, search, filter, and export all subscription data from the ArraySubs admin panel.",
      "arraysubs",
    ),
    icon: FileText,
    isPro: false,
    available: true,
    reports: [
      {
        title: __("All Subscriptions List", "arraysubs"),
        description: __(
          "Sortable list with search, status filtering, bulk actions, and per-page control.",
          "arraysubs",
        ),
        icon: FileText,
        url: arraySubsUrl("/subscriptions"),
        isPro: false,
      },
      {
        title: __("Subscription Detail View", "arraysubs"),
        description: __(
          "Full subscription detail with lifecycle timeline, related orders, meta data, and activity notes.",
          "arraysubs",
        ),
        icon: ClipboardList,
        url: arraySubsUrl("/subscriptions"),
        isPro: false,
      },
      {
        title: __("CSV Export", "arraysubs"),
        description: __(
          "Export all subscriptions to CSV with status and date filters.",
          "arraysubs",
        ),
        icon: FileText,
        url: arraySubsUrl("/subscriptions"),
        isPro: false,
      },
    ],
  },
  {
    id: "manage-members",
    title: __("Member Insights", "arraysubs"),
    description: __(
      "Detailed member profiles with subscription stats, order history, and lifetime value.",
      "arraysubs",
    ),
    icon: UserSearch,
    isPro: true,
    available: hasMemberInsight,
    reports: [
      {
        title: __("Member Profile Dashboard", "arraysubs"),
        description: __(
          "Search any customer to view their subscription stats, active subscriptions, purchased products, and addresses.",
          "arraysubs",
        ),
        icon: UserSearch,
        url: arraySubsUrl("/manage-members"),
        isPro: true,
      },
      {
        title: __("Customer Lifetime Value", "arraysubs"),
        description: __(
          "Per-member lifetime order total, active subscription count, and registration date.",
          "arraysubs",
        ),
        icon: Users,
        url: arraySubsUrl("/manage-members"),
        isPro: true,
      },
    ],
  },
  {
    id: "store-credit",
    title: __("Store Credit", "arraysubs"),
    description: __(
      "Manage and review customer store credit balances and transaction history.",
      "arraysubs",
    ),
    icon: Wallet,
    isPro: true,
    available: hasStoreCredit,
    reports: [
      {
        title: __("Credit Balances", "arraysubs"),
        description: __(
          "Search customers and view/adjust their current store credit balance.",
          "arraysubs",
        ),
        icon: Wallet,
        url: arraySubsUrl("/store-credit"),
        isPro: true,
      },
      {
        title: __("Credit Transaction History", "arraysubs"),
        description: __(
          "Full transaction log of all credits, debits, adjustments, and refunds with date filtering.",
          "arraysubs",
        ),
        icon: FileText,
        url: arraySubsUrl("/store-credit/history"),
        isPro: true,
      },
    ],
  },
  {
    id: "audits",
    title: __("Audit Logs", "arraysubs"),
    description: __(
      "Activity audit trails, webhook delivery logs, and scheduled job execution history.",
      "arraysubs",
    ),
    icon: Activity,
    isPro: true,
    available: hasAudits || hasAutoPayments,
    reports: [
      {
        title: __("Activity Audit Trail", "arraysubs"),
        description: __(
          "All subscription actions with actor, timestamp, entity, and changed values. Filter by role, type, or date.",
          "arraysubs",
        ),
        icon: Activity,
        url: arraySubsUrl("/audits/activity-audits"),
        isPro: true,
      },
      {
        title: __("Gateway Webhook Logs", "arraysubs"),
        description: __(
          "Payment gateway webhook delivery logs and gateway health status.",
          "arraysubs",
        ),
        icon: Box,
        url: arraySubsUrl("/settings/gateways"),
        isPro: true,
        availableCheck: hasAutoPayments,
      },
      {
        title: __("Scheduled Job Logs", "arraysubs"),
        description: __(
          "Action Scheduler execution history — renewals, emails, status changes, and maintenance jobs.",
          "arraysubs",
        ),
        icon: ClipboardList,
        url: arraySubsUrl("/audits/scheduled-job-logs"),
        isPro: true,
      },
    ],
  },
];

const ProBadge = () => (
  <span className="arraysubs-reports__pro-badge">{__("Pro", "arraysubs")}</span>
);

const FreeBadge = () => (
  <span className="arraysubs-reports__free-badge">
    {__("Free", "arraysubs")}
  </span>
);

const ReportCard = ({ report }) => {
  const Icon = report.icon;
  return (
    <a
      href={report.url}
      className="arraysubs-reports__report-card"
      target="_blank"
      rel="noopener noreferrer"
    >
      <div className="arraysubs-reports__report-card-content">
        <div className="arraysubs-reports__report-card-header">
          <h4 className="arraysubs-reports__report-card-title">
            {report.title}
          </h4>
          {report.isPro ? <ProBadge /> : <FreeBadge />}
        </div>
        <p className="arraysubs-reports__report-card-description">
          {report.description}
        </p>
      </div>
      <div className="arraysubs-reports__report-card-arrow">
        <ArrowUpRight size={16} />
      </div>
    </a>
  );
};

const ReportSection = ({ section }) => {
  const Icon = section.icon;
  return (
    <div className="arraysubs-reports__section" id={section.id}>
      <div className="arraysubs-reports__section-header">
        <div className="arraysubs-reports__section-icon">
          <Icon size={22} />
        </div>
        <div className="arraysubs-reports__section-meta">
          <div className="arraysubs-reports__section-title-row">
            <h3 className="arraysubs-reports__section-title">
              {section.title}
            </h3>
            {section.isPro ? <ProBadge /> : <FreeBadge />}
          </div>
          <p className="arraysubs-reports__section-description">
            {section.description}
          </p>
        </div>
      </div>
      <div className="arraysubs-reports__report-grid">
        {section.reports.map((report, index) => (
          <ReportCard key={index} report={report} />
        ))}
      </div>
    </div>
  );
};

const Reports = () => {
  const freeCount = REPORT_SECTIONS.reduce(
    (sum, s) => sum + s.reports.filter((r) => !r.isPro).length,
    0,
  );
  const proCount = REPORT_SECTIONS.reduce(
    (sum, s) => sum + s.reports.filter((r) => r.isPro).length,
    0,
  );

  return (
    <DefaultPageLayout
      title={__("Reports", "arraysubs")}
      subtitle={__(
        "All analytics, reports, and data insights across your subscription business",
        "arraysubs",
      )}
    >
      <div className="arraysubs-reports">
        <div className="arraysubs-reports__summary-bar">
          <div className="arraysubs-reports__summary-stat">
            <BarChart3 size={18} />
            <span>
              {REPORT_SECTIONS.length} {__("report categories", "arraysubs")}
            </span>
          </div>
          <div className="arraysubs-reports__summary-stat">
            <FileText size={18} />
            <span>
              {freeCount + proCount} {__("total reports", "arraysubs")}
            </span>
          </div>
          <div className="arraysubs-reports__summary-stat arraysubs-reports__summary-stat--free">
            <span>
              {freeCount} {__("free", "arraysubs")}
            </span>
          </div>
          <div className="arraysubs-reports__summary-stat arraysubs-reports__summary-stat--pro">
            <Crown size={14} />
            <span>
              {proCount} {__("pro", "arraysubs")}
            </span>
          </div>
        </div>

        <div className="arraysubs-reports__toc">
          <h3 className="arraysubs-reports__toc-title">
            {__("Quick Navigation", "arraysubs")}
          </h3>
          <div className="arraysubs-reports__toc-links">
            {REPORT_SECTIONS.map((section) => {
              const Icon = section.icon;
              return (
                <a
                  key={section.id}
                  href={`#${section.id}`}
                  className="arraysubs-reports__toc-link"
                  onClick={(e) => {
                    e.preventDefault();
                    document
                      .getElementById(section.id)
                      ?.scrollIntoView({ behavior: "smooth" });
                  }}
                >
                  <Icon size={14} />
                  <span>{section.title}</span>
                  {section.isPro && <ProBadge />}
                  <span className="arraysubs-reports__toc-count">
                    {section.reports.length}
                  </span>
                </a>
              );
            })}
          </div>
        </div>

        <div className="arraysubs-reports__sections">
          {REPORT_SECTIONS.map((section) => (
            <ReportSection key={section.id} section={section} />
          ))}
        </div>
      </div>
    </DefaultPageLayout>
  );
};

export default Reports;
