import React, { 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();

  // Handle CSV export
  const handleExport = async () => {
    setExporting(true);
    try {
      const exportUrl = buildUrl(
        `${env?.apiBaseUrl}arraysubs/v1/subscriptions/export`,
        { format: "csv" },
      );
      const response = await fetch(exportUrl, {
        headers: {
          "X-WP-Nonce": env?.nonce,
        },
      });

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

      const result = await response.json();

      if (result.content?.csv) {
        // Create download link
        const blob = new Blob([result.content.csv], {
          type: "text/csv;charset=utf-8;",
        });
        const url = URL.createObjectURL(blob);
        const link = document.createElement("a");
        link.href = url;
        link.download = result.content.filename || "subscriptions-export.csv";
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        URL.revokeObjectURL(url);

        showToast(
          result.message || __("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"
        editUrl="/subscriptions/detail"
        viewComponent={TableView}
        showToast={showToast}
        labels={{
          singular: __("Subscription", "arraysubs"),
          plural: __("Subscriptions", "arraysubs"),
        }}
        searchParams={["search", "customer_search"]}
        searchPlaceholder={__("Customer name, email, username...", "arraysubs")}
        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",
        ]}
        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;
