import React, { useState, useEffect, useCallback } from "react";
import { useParams, useNavigate } from "react-router-dom";
import { __ } from "@wordpress/i18n";
import { Search, DollarSign, Plus, Minus, History } from "lucide-react";
import DefaultPageLayout from "@/components/DefaultPageLayout";
import { ToastContainer } from "@libs/toast";
import { useToast } from "@libs/toast/useToast";
import { Skeleton } from "@libs/skeleton";

/**
 * Store Credit Management Page
 *
 * Admin page for managing customer store credits.
 * Features: Search customers, view balance, adjust credits, view history.
 */
const StoreCreditManagement = () => {
  const { env } = window.arraySubs || {};
  const { toasts, showToast, removeToast } = useToast();
  const { userId } = useParams();
  const navigate = useNavigate();

  // State
  const [searchQuery, setSearchQuery] = useState("");
  const [searchResults, setSearchResults] = useState([]);
  const [searching, setSearching] = useState(false);
  const [selectedCustomer, setSelectedCustomer] = useState(null);
  const [customerData, setCustomerData] = useState(null);
  const [loadingCustomer, setLoadingCustomer] = useState(false);
  const [adjustmentAmount, setAdjustmentAmount] = useState("");
  const [adjustmentType, setAdjustmentType] = useState("add");
  const [adjustmentNote, setAdjustmentNote] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [historyPage, setHistoryPage] = useState(1);

  // Search customers
  const searchCustomers = useCallback(async () => {
    if (searchQuery.length < 2) {
      setSearchResults([]);
      return;
    }

    setSearching(true);
    try {
      const response = await fetch(
        `${
          env?.apiBaseUrl
        }arraysubs/v1/credits/search?query=${encodeURIComponent(searchQuery)}`,
        {
          headers: {
            "X-WP-Nonce": env?.nonce,
          },
        },
      );

      const data = await response.json();
      if (data.success) {
        setSearchResults(data.data);
      } else {
        setSearchResults([]);
      }
    } catch (error) {
      console.error("Search error:", error);
      showToast(__("Failed to search customers", "arraysubs"), "error");
    } finally {
      setSearching(false);
    }
  }, [searchQuery, env]);

  // Debounce search
  useEffect(() => {
    const timer = setTimeout(() => {
      searchCustomers();
    }, 300);

    return () => clearTimeout(timer);
  }, [searchQuery, searchCustomers]);

  // Auto-load customer from URL param
  useEffect(() => {
    if (userId && !selectedCustomer) {
      const numericId = parseInt(userId, 10);
      if (numericId > 0) {
        setSelectedCustomer({ id: numericId });
        loadCustomerData(numericId);
      }
    }
  }, [userId]); // eslint-disable-line react-hooks/exhaustive-deps

  // Load customer data
  const loadCustomerData = useCallback(
    async (customerId, page = 1) => {
      setLoadingCustomer(true);
      try {
        const response = await fetch(
          `${env?.apiBaseUrl}arraysubs/v1/credits/customer/${customerId}?page=${page}&per_page=10`,
          {
            headers: {
              "X-WP-Nonce": env?.nonce,
            },
          },
        );

        const data = await response.json();
        if (data.success) {
          setCustomerData(data.data);
          setHistoryPage(page);
        } else {
          showToast(
            data.message || __("Failed to load customer data", "arraysubs"),
            "error",
          );
        }
      } catch (error) {
        console.error("Load customer error:", error);
        showToast(__("Failed to load customer data", "arraysubs"), "error");
      } finally {
        setLoadingCustomer(false);
      }
    },
    [env],
  );

  // Select customer
  const handleSelectCustomer = (customer) => {
    setSelectedCustomer(customer);
    setSearchResults([]);
    setSearchQuery("");
    navigate(`/store-credit/${customer.id}`);
    loadCustomerData(customer.id);
  };

  // Adjust credit
  const handleAdjustCredit = async () => {
    if (!selectedCustomer || !adjustmentAmount) {
      showToast(__("Please enter an amount", "arraysubs"), "error");
      return;
    }

    const amount = parseFloat(adjustmentAmount);
    if (isNaN(amount) || amount <= 0) {
      showToast(__("Please enter a valid amount", "arraysubs"), "error");
      return;
    }

    // Check if deducting more than available
    if (adjustmentType === "deduct" && amount > customerData?.balance) {
      showToast(
        __("Cannot deduct more than available balance", "arraysubs"),
        "error",
      );
      return;
    }

    setSubmitting(true);
    try {
      const finalAmount = adjustmentType === "add" ? amount : -amount;

      const response = await fetch(
        `${env?.apiBaseUrl}arraysubs/v1/credits/adjust`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            "X-WP-Nonce": env?.nonce,
          },
          body: JSON.stringify({
            customer_id: selectedCustomer.id,
            amount: finalAmount,
            note: adjustmentNote,
          }),
        },
      );

      const data = await response.json();
      if (data.success) {
        showToast(data.message, "success");
        // Reload customer data
        loadCustomerData(selectedCustomer.id, 1);
        // Reset form
        setAdjustmentAmount("");
        setAdjustmentNote("");
      } else {
        showToast(
          data.message || __("Failed to adjust credit", "arraysubs"),
          "error",
        );
      }
    } catch (error) {
      console.error("Adjust credit error:", error);
      showToast(__("Failed to adjust credit", "arraysubs"), "error");
    } finally {
      setSubmitting(false);
    }
  };

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

  return (
    <DefaultPageLayout
      title={__("Store Credit Management", "arraysubs")}
      subtitle={__("Manage customer store credits", "arraysubs")}
    >
      <div className="arraysubs-store-credit">
        {/* Search Section */}
        <div className="arraysubs-store-credit__search-section">
          <div className="arraysubs-store-credit__search-box">
            <label htmlFor="customer-search">
              <Search size={16} />
              {__("Find a Customer", "arraysubs")}
            </label>
            <div className="arraysubs-store-credit__search-input-wrapper">
              <input
                id="customer-search"
                type="text"
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                placeholder={__(
                  "Search by name, username, or email...",
                  "arraysubs",
                )}
                className="arraysubs-store-credit__search-input"
              />
              {searching && (
                <span className="arraysubs-store-credit__searching">
                  {__("Searching...", "arraysubs")}
                </span>
              )}
            </div>

            {/* Search Results Dropdown */}
            {searchResults.length > 0 && (
              <div className="arraysubs-store-credit__search-results">
                {searchResults.map((customer) => (
                  <button
                    key={customer.id}
                    type="button"
                    className="arraysubs-store-credit__search-result-item"
                    onClick={() => handleSelectCustomer(customer)}
                  >
                    <div className="arraysubs-store-credit__result-info">
                      <span className="arraysubs-store-credit__customer-name">
                        {customer.display_name}
                      </span>
                      <span className="arraysubs-store-credit__customer-meta">
                        {customer.email}
                        {customer.username ? ` · @${customer.username}` : ""}
                      </span>
                    </div>
                    <div className="arraysubs-store-credit__result-stats">
                      <span className="arraysubs-store-credit__customer-balance">
                        {formatCurrency(customer.balance)}
                      </span>
                    </div>
                  </button>
                ))}
              </div>
            )}
          </div>
        </div>

        {/* Selected Customer Section */}
        {selectedCustomer && (
          <div className="arraysubs-store-credit__customer-section">
            {loadingCustomer ? (
              <Skeleton height={200} />
            ) : customerData ? (
              <>
                {/* Customer Header */}
                <div className="arraysubs-store-credit__customer-header">
                  <div className="arraysubs-store-credit__customer-info">
                    <h3>
                      {__("Customer:", "arraysubs")}{" "}
                      {customerData.customer.display_name}
                    </h3>
                    <p>{customerData.customer.email}</p>
                  </div>
                  <div className="arraysubs-store-credit__customer-actions">
                    <button
                      className="button button-secondary"
                      onClick={() =>
                        navigate(`/manage-members/${customerData.customer.id}`)
                      }
                    >
                      {__("Member Details", "arraysubs")}
                    </button>
                    <button
                      className="button button-link-delete"
                      onClick={() => {
                        setSelectedCustomer(null);
                        setCustomerData(null);
                      }}
                    >
                      {__("Clear", "arraysubs")}
                    </button>
                  </div>
                </div>

                {/* Balance Display */}
                <div className="arraysubs-store-credit__balance-card">
                  <div className="arraysubs-store-credit__balance-label">
                    {__("Current Credit Balance", "arraysubs")}
                  </div>
                  <div className="arraysubs-store-credit__balance-amount">
                    <DollarSign size={28} />
                    {parseFloat(customerData.balance).toFixed(2)}
                  </div>
                </div>

                {/* Adjustment Form */}
                <div className="arraysubs-store-credit__adjustment-section">
                  <h4>{__("Adjust Credit:", "arraysubs")}</h4>
                  <div className="arraysubs-store-credit__adjustment-form">
                    <div className="arraysubs-store-credit__adjustment-amount">
                      <label>{__("Amount:", "arraysubs")}</label>
                      <input
                        type="number"
                        min="0"
                        step="0.01"
                        value={adjustmentAmount}
                        onChange={(e) => setAdjustmentAmount(e.target.value)}
                        placeholder="0.00"
                      />
                    </div>
                    <div className="arraysubs-store-credit__adjustment-type">
                      <label>{__("Type:", "arraysubs")}</label>
                      <div className="arraysubs-store-credit__radio-group">
                        <label>
                          <input
                            type="radio"
                            name="adjustmentType"
                            value="add"
                            checked={adjustmentType === "add"}
                            onChange={(e) => setAdjustmentType(e.target.value)}
                          />
                          <Plus size={16} />
                          {__("Add", "arraysubs")}
                        </label>
                        <label>
                          <input
                            type="radio"
                            name="adjustmentType"
                            value="deduct"
                            checked={adjustmentType === "deduct"}
                            onChange={(e) => setAdjustmentType(e.target.value)}
                          />
                          <Minus size={16} />
                          {__("Deduct", "arraysubs")}
                        </label>
                      </div>
                    </div>
                    <div className="arraysubs-store-credit__adjustment-note">
                      <label>{__("Note:", "arraysubs")}</label>
                      <input
                        type="text"
                        value={adjustmentNote}
                        onChange={(e) => setAdjustmentNote(e.target.value)}
                        placeholder={__("Reason for adjustment", "arraysubs")}
                      />
                    </div>
                    <button
                      className="button button-primary"
                      onClick={handleAdjustCredit}
                      disabled={submitting || !adjustmentAmount}
                    >
                      {submitting
                        ? __("Processing...", "arraysubs")
                        : __("Apply Adjustment", "arraysubs")}
                    </button>
                  </div>
                </div>

                {/* Credit History */}
                <div className="arraysubs-store-credit__history-section">
                  <h4>
                    <History size={18} />
                    {__("Credit History:", "arraysubs")}
                  </h4>
                  {customerData.history && customerData.history.length > 0 ? (
                    <>
                      <table className="arraysubs-store-credit__history-table">
                        <thead>
                          <tr>
                            <th>{__("Date", "arraysubs")}</th>
                            <th>{__("Description", "arraysubs")}</th>
                            <th>{__("Amount", "arraysubs")}</th>
                            <th>{__("Balance After", "arraysubs")}</th>
                          </tr>
                        </thead>
                        <tbody>
                          {customerData.history.map((item) => (
                            <tr key={item.id}>
                              <td>{item.date_formatted}</td>
                              <td>
                                <span className="arraysubs-store-credit__source-label">
                                  {item.source_label}
                                </span>
                                {item.note && (
                                  <span className="arraysubs-store-credit__note">
                                    {item.note}
                                  </span>
                                )}
                              </td>
                              <td
                                className={`arraysubs-store-credit__amount ${
                                  item.type === "credit"
                                    ? "arraysubs-store-credit__amount--credit"
                                    : "arraysubs-store-credit__amount--debit"
                                }`}
                              >
                                {item.type === "credit" ? "+" : "-"}
                                {formatCurrency(item.amount)}
                              </td>
                              <td>{formatCurrency(item.balance_after)}</td>
                            </tr>
                          ))}
                        </tbody>
                      </table>

                      {/* Pagination */}
                      {customerData.pages > 1 && (
                        <div className="arraysubs-store-credit__pagination">
                          <button
                            className="button"
                            disabled={historyPage <= 1}
                            onClick={() =>
                              loadCustomerData(
                                selectedCustomer.id,
                                historyPage - 1,
                              )
                            }
                          >
                            {__("« Prev", "arraysubs")}
                          </button>
                          <span>
                            {__("Page", "arraysubs")} {historyPage}{" "}
                            {__("of", "arraysubs")} {customerData.pages}
                          </span>
                          <button
                            className="button"
                            disabled={historyPage >= customerData.pages}
                            onClick={() =>
                              loadCustomerData(
                                selectedCustomer.id,
                                historyPage + 1,
                              )
                            }
                          >
                            {__("Next »", "arraysubs")}
                          </button>
                        </div>
                      )}
                    </>
                  ) : (
                    <p className="arraysubs-store-credit__no-history">
                      {__("No credit history found.", "arraysubs")}
                    </p>
                  )}
                </div>
              </>
            ) : null}
          </div>
        )}

        {/* No Customer Selected */}
        {!selectedCustomer && (
          <div className="arraysubs-store-credit__empty-state">
            <DollarSign size={48} />
            <p>
              {__(
                "Search for a customer above to view and manage their store credit.",
                "arraysubs",
              )}
            </p>
          </div>
        )}
      </div>

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

export default StoreCreditManagement;
