import React, { useMemo, useState } from "react";
import { useNavigate } from "react-router-dom";
import { __ } from "@wordpress/i18n";
import DataList from "@libs/data-list";
import TableView from "@libs/data-list/TableView";
import DefaultPageLayout from "@/components/DefaultPageLayout";
import { ToastContainer, useToast } from "@libs/toast";
import { buildUrl } from "@libs/url";

const SubscriptionsList = () => {
  const { env } = window.arraySubs;
  const navigate = useNavigate();
  const [exporting, setExporting] = useState(false);
  const { toasts, showToast, removeToast } = useToast();
  const gatewayFilters = useMemo(
    () => [
      {
        key: "gateway",
        label: __("Gateway", "arraysubs"),
        options: [
          { value: "", label: __("All Gateways", "arraysubs") },
          { value: "stripe", label: __("Stripe", "arraysubs") },
          { value: "paypal", label: __("PayPal", "arraysubs") },
          { value: "paddle", label: __("Paddle", "arraysubs") },
        ],
      },
    ],
    [],
  );
  const addProductUrl = env?.wpAdminUrl
    ? buildUrl(`${env.wpAdminUrl}post-new.php`, { post_type: "product" })
    : "post-new.php?post_type=product";

  const renderEmptyState = () => (
    <div className="arraysubs-subscriptions-empty">
      <div className="arraysubs-subscriptions-empty__content">
        <p className="arraysubs-subscriptions-empty__eyebrow">
          {__("Get started", "arraysubs")}
        </p>
        <h2 className="arraysubs-subscriptions-empty__title">
          {__("Create a subscription product first", "arraysubs")}
        </h2>
        <p className="arraysubs-subscriptions-empty__description">
          {__(
            "To start managing subscriptions, you need to create a subscription product first. Follow the steps below to set up your first subscription product. ArraySubs uses standard WooCommerce products to handle subscriptions. When you create a new product, you just need to check the 'Subscription' box in the product meta tab.",
            "arraysubs",
          )}
        </p>

        <ol className="arraysubs-subscriptions-empty__steps">
          <li>
            <strong>{__("Open Products -> Add New.", "arraysubs")}</strong>{" "}
            {__(
              "Create the product customers will buy to start a subscription.",
              "arraysubs",
            )}
          </li>
          <li>
            <strong>
              {__("Enable the subscription product settings.", "arraysubs")}
            </strong>{" "}
            {__(
              "Configure the billing interval, renewal price, sign-up fee, trial, and subscription length as needed.",
              "arraysubs",
            )}
          </li>
          <li>
            <strong>{__("Publish and test checkout.", "arraysubs")}</strong>{" "}
            {__(
              "After a customer completes checkout, the subscription record is created and listed on this page.",
              "arraysubs",
            )}
          </li>
        </ol>

        <div className="arraysubs-subscriptions-empty__actions">
          <a href={addProductUrl} className="button button-primary">
            {__("Create subscription product", "arraysubs")}
          </a>
          <a
            href="https://support.arrayhash.com/arraysubs/subscription-products/"
            target="_blank"
            rel="noopener noreferrer"
            className="button button-secondary"
          >
            {__("Read subscription product guide", "arraysubs")}
          </a>
        </div>
      </div>
    </div>
  );

  // Handle CSV export
  const handleExport = async ({ statusFilter } = {}) => {
    setExporting(true);
    try {
      const params = { format: "csv" };

      if (statusFilter && statusFilter !== "all") {
        params.status = statusFilter;
      }

      const exportUrl = buildUrl(
        `${env?.apiBaseUrl}arraysubs/v1/subscriptions/export`,
        params,
      );
      const response = await fetch(exportUrl, {
        headers: {
          "X-WP-Nonce": env?.nonce,
        },
      });

      if (!response.ok) {
        throw new Error(__("Failed to export subscriptions", "arraysubs"));
      }

      const disposition = response.headers.get("Content-Disposition") || "";
      const filenameMatch = disposition.match(/filename="?([^";]+)"?/i);
      const filename = filenameMatch
        ? filenameMatch[1]
        : "subscriptions-export.csv";
      const blob = await response.blob();
      const url = URL.createObjectURL(blob);
      const link = document.createElement("a");

      link.href = url;
      link.download = filename;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(url);

      showToast(__("Export completed successfully", "arraysubs"), "success");
    } catch (error) {
      console.error("Export error:", error);
      showToast(error.message, "error");
    } finally {
      setExporting(false);
    }
  };

  return (
    <DefaultPageLayout
      title={__("Subscriptions", "arraysubs")}
      subtitle={__("Manage customer subscriptions", "arraysubs")}
    >
      <DataList
        cptSlug="arraysubs_data"
        dataSource="post_type"
        addUrl="/subscriptions/form"
        addButtonLabel={__("Add new subscription", "arraysubs")}
        editUrl="/subscriptions/detail"
        viewComponent={TableView}
        showToast={showToast}
        renderEmptyState={renderEmptyState}
        labels={{
          singular: __("Subscription", "arraysubs"),
          plural: __("Subscriptions", "arraysubs"),
        }}
        searchParams={["customer_search"]}
        searchPlaceholder={__("Customer name, email, username...", "arraysubs")}
        filters={gatewayFilters}
        syncUrlState={true}
        customButtons={[
          {
            label: exporting
              ? __("Exporting...", "arraysubs")
              : __("Export CSV", "arraysubs"),
            onClick: handleExport,
            className: "button-secondary",
            disabled: exporting,
          },
        ]}
        allowedActions={["delete"]}
        allStatuses={[
          "arraysubs-active",
          "arraysubs-pending",
          "arraysubs-on-hold",
          "arraysubs-cancelled",
          "arraysubs-expired",
          "arraysubs-trial",
        ]}
        onDeleteCheck={(item) => {
          const status = item.status;
          if (status === "arraysubs-active" || status === "arraysubs-trial") {
            return {
              allowed: false,
              message: __(
                "Cannot delete active or trial subscriptions. Please cancel the subscription first.",
                "arraysubs",
              ),
            };
          }
          return { allowed: true };
        }}
        onDeleteWarnMsg={(item) =>
          __(
            "Are you sure you want to permanently delete this subscription? This action cannot be undone.",
            "arraysubs",
          )
        }
        perPage={20}
        restUrl={env?.apiBaseUrl}
        nonce={env?.nonce}
        columns={["status", "date"]}
        metaColumns={[
          "_customer_display",
          "_product_display",
          "_next_payment_display",
        ]}
        columnOrder={[
          "status",
          "date",
          "_customer_display",
          "_product_display",
          "_next_payment_display",
        ]}
        includeTitleColumn={false}
        columnFormats={{
          status: {
            type: "tag",
            label: __("Status", "arraysubs"),
            labels: {
              "arraysubs-active": __("Active", "arraysubs"),
              "arraysubs-pending": __("Pending", "arraysubs"),
              "arraysubs-on-hold": __("On Hold", "arraysubs"),
              "arraysubs-cancelled": __("Cancelled", "arraysubs"),
              "arraysubs-expired": __("Expired", "arraysubs"),
              "arraysubs-trial": __("Trial", "arraysubs"),
            },
            classes: {
              "arraysubs-active": "arraysubs-dl-tag--active",
              "arraysubs-pending": "arraysubs-dl-tag--pending",
              "arraysubs-on-hold": "arraysubs-dl-tag--on-hold",
              "arraysubs-cancelled": "arraysubs-dl-tag--cancelled",
              "arraysubs-expired": "arraysubs-dl-tag--expired",
              "arraysubs-trial": "arraysubs-dl-tag--trial",
            },
          },
          _customer_display: {
            type: "stacked",
            label: __("Customer", "arraysubs"),
          },
          _product_display: {
            type: "stacked",
            label: __("Product", "arraysubs"),
          },
          _next_payment_display: {
            type: "stacked",
            label: __("Next Payment", "arraysubs"),
          },
        }}
        statusList={[
          { status: "all", label: __("All", "arraysubs") },
          {
            status: "arraysubs-active",
            label: __("Active", "arraysubs"),
          },
          {
            status: "arraysubs-pending",
            label: __("Pending", "arraysubs"),
          },
          {
            status: "arraysubs-on-hold",
            label: __("On Hold", "arraysubs"),
          },
          {
            status: "arraysubs-cancelled",
            label: __("Cancelled", "arraysubs"),
          },
          {
            status: "arraysubs-expired",
            label: __("Expired", "arraysubs"),
          },
          {
            status: "arraysubs-trial",
            label: __("Trial", "arraysubs"),
          },
        ]}
        customActions={[
          {
            key: "view-details",
            label: __("View Details", "arraysubs"),
            onClick: (item) => {
              navigate(`/subscriptions/detail/${item.id}`);
            },
            icon: "eye",
          },
          {
            key: "edit",
            label: __("Edit", "arraysubs"),
            onClick: (item) => {
              navigate(`/subscriptions/edit/${item.id}`);
            },
            icon: "edit",
          },
        ]}
        isFeaturedImage={false}
      />
      <ToastContainer toasts={toasts} removeToast={removeToast} />
    </DefaultPageLayout>
  );
};

export default SubscriptionsList;
