import React, { useState, useEffect, useCallback } from "react";
import { __ } from "@wordpress/i18n";
import { History, Trash2, Filter } from "lucide-react";
import DefaultPageLayout from "@/components/DefaultPageLayout";
import { ToastContainer } from "@libs/toast";
import { useToast } from "@libs/toast/useToast";
import { Skeleton } from "@libs/skeleton";
import Modal from "@libs/modal";
import { buildRestUrl } from "@libs/url";

/**
 * Credit History Page
 *
 * Admin page for viewing all credit transactions.
 * Features: Filter by source/type, pagination, delete entries.
 */
const CreditHistory = () => {
  const { env } = window.arraySubs || {};
  const { toasts, showToast, removeToast } = useToast();

  // State
  const [loading, setLoading] = useState(true);
  const [history, setHistory] = useState([]);
  const [totalItems, setTotalItems] = useState(0);
  const [totalPages, setTotalPages] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [perPage] = useState(20);
  const [sourceFilter, setSourceFilter] = useState("");
  const [typeFilter, setTypeFilter] = useState("");
  const [deleteModalOpen, setDeleteModalOpen] = useState(false);
  const [deletingItem, setDeletingItem] = useState(null);
  const [deleting, setDeleting] = useState(false);

  // Source options
  const sourceOptions = [
    { value: "", label: __("All Sources", "arraysubs") },
    { value: "downgrade", label: __("Plan Downgrade", "arraysubs") },
    { value: "refund", label: __("Refund", "arraysubs") },
    { value: "admin", label: __("Admin Adjustment", "arraysubs") },
    { value: "promotional", label: __("Promotional", "arraysubs") },
    { value: "purchase", label: __("Credit Purchase", "arraysubs") },
    { value: "renewal_applied", label: __("Applied to Renewal", "arraysubs") },
    { value: "order_applied", label: __("Applied to Order", "arraysubs") },
    { value: "expired", label: __("Expired", "arraysubs") },
  ];

  // Type options
  const typeOptions = [
    { value: "", label: __("All Types", "arraysubs") },
    { value: "credit", label: __("Credit (Added)", "arraysubs") },
    { value: "debit", label: __("Debit (Deducted)", "arraysubs") },
  ];

  // Load history
  const loadHistory = useCallback(
    async (page = 1) => {
      setLoading(true);
      try {
        const url = buildRestUrl(env?.apiBaseUrl, "arraysubs/v1/credits/history", {
          page,
          per_page: perPage,
          source: sourceFilter,
          type: typeFilter,
        });

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

        const data = await response.json();
        if (data.success) {
          setHistory(data.data.items);
          setTotalItems(data.data.total);
          setTotalPages(data.data.pages);
          setCurrentPage(page);
        } else {
          showToast(
            data.message || __("Failed to load history", "arraysubs"),
            "error",
          );
        }
      } catch (error) {
        console.error("Load history error:", error);
        showToast(__("Failed to load history", "arraysubs"), "error");
      } finally {
        setLoading(false);
      }
    },
    [env, sourceFilter, typeFilter, perPage],
  );

  // Initial load
  useEffect(() => {
    loadHistory(1);
  }, [sourceFilter, typeFilter]);

  // Delete log entry
  const handleDelete = async () => {
    if (!deletingItem) return;

    setDeleting(true);
    try {
      const response = await fetch(
        buildRestUrl(env?.apiBaseUrl, `arraysubs/v1/credits/log/${deletingItem.id}`),
        {
          method: "DELETE",
          headers: {
            "X-WP-Nonce": env?.nonce,
          },
        },
      );

      const data = await response.json();
      if (data.success) {
        showToast(__("Log entry deleted", "arraysubs"), "success");
        setDeleteModalOpen(false);
        setDeletingItem(null);
        loadHistory(currentPage);
      } else {
        showToast(
          data.message || __("Failed to delete entry", "arraysubs"),
          "error",
        );
      }
    } catch (error) {
      console.error("Delete error:", error);
      showToast(__("Failed to delete entry", "arraysubs"), "error");
    } finally {
      setDeleting(false);
    }
  };

  // Format currency
  const formatCurrency = (amount) => {
    return `$${parseFloat(amount).toFixed(2)}`;
  };

  return (
    <DefaultPageLayout
      title={__("All Credit Transactions", "arraysubs")}
      subtitle={__(
        "View and manage all store credit transactions",
        "arraysubs",
      )}
    >
      <div className="arraysubs-credit-history">
        {/* Filters */}
        <div className="arraysubs-credit-history__filters">
          <div className="arraysubs-credit-history__filter-group">
            <label>
              <Filter size={16} />
              {__("Filters:", "arraysubs")}
            </label>
            <select
              value={sourceFilter}
              onChange={(e) => setSourceFilter(e.target.value)}
            >
              {sourceOptions.map((option) => (
                <option key={option.value} value={option.value}>
                  {option.label}
                </option>
              ))}
            </select>
            <select
              value={typeFilter}
              onChange={(e) => setTypeFilter(e.target.value)}
            >
              {typeOptions.map((option) => (
                <option key={option.value} value={option.value}>
                  {option.label}
                </option>
              ))}
            </select>
          </div>
          <div className="arraysubs-credit-history__total">
            {__("Total:", "arraysubs")} {totalItems}{" "}
            {__("transactions", "arraysubs")}
          </div>
        </div>

        {/* Table */}
        {loading ? (
          <Skeleton height={400} />
        ) : history.length > 0 ? (
          <>
            <table className="arraysubs-credit-history__table">
              <thead>
                <tr>
                  <th>{__("ID", "arraysubs")}</th>
                  <th>{__("Date", "arraysubs")}</th>
                  <th>{__("Customer", "arraysubs")}</th>
                  <th>{__("Description", "arraysubs")}</th>
                  <th>{__("Amount", "arraysubs")}</th>
                  <th>{__("Actions", "arraysubs")}</th>
                </tr>
              </thead>
              <tbody>
                {history.map((item) => (
                  <tr key={item.id}>
                    <td>#{item.id}</td>
                    <td>{item.date_formatted}</td>
                    <td>
                      <div className="arraysubs-credit-history__customer">
                        <span className="arraysubs-credit-history__customer-name">
                          {item.customer_name}
                        </span>
                        <span className="arraysubs-credit-history__customer-email">
                          {item.customer_email}
                        </span>
                      </div>
                    </td>
                    <td>
                      <span className="arraysubs-credit-history__source-label">
                        {item.source_label}
                      </span>
                      {item.note && (
                        <span className="arraysubs-credit-history__note">
                          {item.note}
                        </span>
                      )}
                      {item.subscription_id > 0 && (
                        <span className="arraysubs-credit-history__subscription">
                          {__("Subscription:", "arraysubs")} #
                          {item.subscription_id}
                        </span>
                      )}
                    </td>
                    <td
                      className={`arraysubs-credit-history__amount ${
                        item.type === "credit"
                          ? "arraysubs-credit-history__amount--credit"
                          : "arraysubs-credit-history__amount--debit"
                      }`}
                    >
                      {item.type === "credit" ? "+" : "-"}
                      {formatCurrency(item.amount)}
                    </td>
                    <td>
                      <button
                        className="button button-link-delete"
                        onClick={() => {
                          setDeletingItem(item);
                          setDeleteModalOpen(true);
                        }}
                        title={__("Delete", "arraysubs")}
                      >
                        <Trash2 size={16} />
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>

            {/* Pagination */}
            {totalPages > 1 && (
              <div className="arraysubs-credit-history__pagination">
                <button
                  className="button"
                  disabled={currentPage <= 1}
                  onClick={() => loadHistory(currentPage - 1)}
                >
                  {__("« Prev", "arraysubs")}
                </button>
                <span>
                  {__("Page", "arraysubs")} {currentPage}{" "}
                  {__("of", "arraysubs")} {totalPages}
                </span>
                <button
                  className="button"
                  disabled={currentPage >= totalPages}
                  onClick={() => loadHistory(currentPage + 1)}
                >
                  {__("Next »", "arraysubs")}
                </button>
              </div>
            )}
          </>
        ) : (
          <div className="arraysubs-credit-history__empty">
            <History size={48} />
            <p>{__("No credit transactions found.", "arraysubs")}</p>
          </div>
        )}

        {/* Note */}
        <div className="arraysubs-credit-history__note-box">
          <p>
            <strong>{__("Note:", "arraysubs")}</strong>{" "}
            {__(
              "This log is read-only. Deleting entries only removes the log record, it does not affect actual credit balances.",
              "arraysubs",
            )}
          </p>
        </div>
      </div>

      {/* Delete Confirmation Modal */}
      <Modal
        isOpen={deleteModalOpen}
        onClose={() => {
          setDeleteModalOpen(false);
          setDeletingItem(null);
        }}
        title={__("Delete Log Entry", "arraysubs")}
      >
        <div className="arraysubs-credit-history__delete-modal">
          <p>
            {__(
              "Are you sure you want to delete this log entry? This action cannot be undone.",
              "arraysubs",
            )}
          </p>
          {deletingItem && (
            <div className="arraysubs-credit-history__delete-details">
              <p>
                <strong>{__("Transaction:", "arraysubs")}</strong> #
                {deletingItem.id}
              </p>
              <p>
                <strong>{__("Customer:", "arraysubs")}</strong>{" "}
                {deletingItem.customer_name}
              </p>
              <p>
                <strong>{__("Amount:", "arraysubs")}</strong>{" "}
                {deletingItem.type === "credit" ? "+" : "-"}
                {formatCurrency(deletingItem.amount)}
              </p>
            </div>
          )}
          <div className="arraysubs-credit-history__delete-actions">
            <button
              className="button"
              onClick={() => {
                setDeleteModalOpen(false);
                setDeletingItem(null);
              }}
              disabled={deleting}
            >
              {__("Cancel", "arraysubs")}
            </button>
            <button
              className="button button-link-delete"
              onClick={handleDelete}
              disabled={deleting}
            >
              {deleting
                ? __("Deleting...", "arraysubs")
                : __("Delete", "arraysubs")}
            </button>
          </div>
        </div>
      </Modal>

      <ToastContainer toasts={toasts} removeToast={removeToast} />
    </DefaultPageLayout>
  );
};

export default CreditHistory;
