/**
 * Manage Members - Member Insight Page
 *
 * Search for members and view comprehensive details about their
 * subscriptions, orders, purchased products, and account information.
 *
 * @package ArraySubsPro
 */

import React, { useState, useEffect, useCallback } from "react";
import { useParams, useNavigate } from "react-router-dom";
import { __ } from "@wordpress/i18n";
import {
  Search,
  User,
  Mail,
  Phone,
  MapPin,
  ShoppingCart,
  Repeat,
  CreditCard,
  Package,
  DollarSign,
  Calendar,
  ExternalLink,
  X,
  ChevronDown,
  ChevronUp,
  UserSearch,
  Wallet,
  ArrowRight,
  LogIn,
} from "lucide-react";
import DefaultPageLayout from "@/components/DefaultPageLayout";
import { buildUrl } from "@/libs/url";
import { Skeleton } from "@libs/skeleton";
import { ToastContainer } from "@libs/toast";
import { useToast } from "@libs/toast/useToast";

/**
 * Status badge color mapping
 */
const STATUS_COLORS = {
  "arraysubs-active": { bg: "#e6f6e6", color: "#007017", label: "Active" },
  "arraysubs-cancelled": { bg: "#fce4e4", color: "#a00", label: "Cancelled" },
  "arraysubs-on-hold": { bg: "#fff3cd", color: "#856404", label: "On Hold" },
  "arraysubs-expired": { bg: "#f0f0f0", color: "#646970", label: "Expired" },
  "arraysubs-pending": { bg: "#e7f3fe", color: "#0a58ca", label: "Pending" },
  "arraysubs-paused": { bg: "#fff3cd", color: "#856404", label: "Paused" },
  "arraysubs-trial": { bg: "#e0f2fe", color: "#0369a1", label: "Trial" },
};

/**
 * StatusBadge component
 */
const StatusBadge = ({ status, map }) => {
  const config = map[status] || {
    bg: "#f0f0f0",
    color: "#646970",
    label: status,
  };
  return (
    <span
      className="arraysubs-member-insight__badge"
      style={{ background: config.bg, color: config.color }}
    >
      {config.label}
    </span>
  );
};

/**
 * Collapsible section component
 */
const CollapsibleSection = ({
  title,
  icon: Icon,
  count,
  defaultOpen = true,
  children,
}) => {
  const [open, setOpen] = useState(defaultOpen);
  return (
    <div
      className={`arraysubs-member-insight__section ${
        open ? "arraysubs-member-insight__section--open" : ""
      }`}
    >
      <button
        type="button"
        className="arraysubs-member-insight__section-header"
        onClick={() => setOpen(!open)}
      >
        <div className="arraysubs-member-insight__section-title">
          {Icon && <Icon size={18} />}
          <span>{title}</span>
          {typeof count === "number" && (
            <span className="arraysubs-member-insight__section-count">
              {count}
            </span>
          )}
        </div>
        {open ? <ChevronUp size={18} /> : <ChevronDown size={18} />}
      </button>
      {open && (
        <div className="arraysubs-member-insight__section-body">{children}</div>
      )}
    </div>
  );
};

/**
 * Address formatter
 */
const formatAddress = (addr) => {
  if (!addr) return null;
  const parts = [
    addr.address_1,
    addr.address_2,
    [addr.city, addr.state, addr.postcode].filter(Boolean).join(", "),
    addr.country,
  ].filter(Boolean);
  return parts.length > 0 ? parts.join("\n") : null;
};

/**
 * ManageMembers Component
 */
const ManageMembers = () => {
  const { env } = window.arraySubs || {};
  const { toasts, showToast, removeToast } = useToast();
  const { userId } = useParams();
  const navigate = useNavigate();

  const [searchQuery, setSearchQuery] = useState("");
  const [searchResults, setSearchResults] = useState([]);
  const [searching, setSearching] = useState(false);
  const [selectedUser, setSelectedUser] = useState(null);
  const [memberData, setMemberData] = useState(null);
  const [loadingMember, setLoadingMember] = useState(false);

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

    setSearching(true);
    try {
      const response = await fetch(
        `${
          env?.apiBaseUrl
        }arraysubs/v1/members/search?query=${encodeURIComponent(searchQuery)}`,
        { headers: { "X-WP-Nonce": env?.nonce } },
      );
      const data = await response.json();
      if (data.success) {
        setSearchResults(data.data);
      } else {
        setSearchResults([]);
      }
    } catch {
      showToast(__("Failed to search members", "arraysubs"), "error");
    } finally {
      setSearching(false);
    }
  }, [searchQuery, env]);

  // Debounced search
  useEffect(() => {
    const timer = setTimeout(() => {
      searchMembers();
    }, 300);
    return () => clearTimeout(timer);
  }, [searchQuery, searchMembers]);

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

  // Load member details
  const loadMemberDetails = useCallback(
    async (userId) => {
      setLoadingMember(true);
      try {
        const response = await fetch(
          `${env?.apiBaseUrl}arraysubs/v1/members/${userId}`,
          { headers: { "X-WP-Nonce": env?.nonce } },
        );
        const data = await response.json();
        if (data.success) {
          setMemberData(data.data);
        } else {
          showToast(
            data.message || __("Failed to load member data", "arraysubs"),
            "error",
          );
        }
      } catch {
        showToast(__("Failed to load member data", "arraysubs"), "error");
      } finally {
        setLoadingMember(false);
      }
    },
    [env],
  );

  // Select user from search
  const handleSelectUser = (user) => {
    setSelectedUser(user);
    setSearchResults([]);
    setSearchQuery("");
    navigate(`/manage-members/${user.id}`);
    loadMemberDetails(user.id);
  };

  // Clear selection
  const handleClear = () => {
    setSelectedUser(null);
    setMemberData(null);
    navigate("/manage-members");
  };

  return (
    <DefaultPageLayout
      title={__("Manage Members", "arraysubs")}
      subtitle={__(
        "Search and view detailed member subscription insights",
        "arraysubs",
      )}
      icon={<UserSearch size={24} />}
    >
      <div className="arraysubs-member-insight">
        {/* Search */}
        <div className="arraysubs-member-insight__search-card">
          <div className="arraysubs-member-insight__search-box">
            <label htmlFor="member-search">
              <Search size={16} />
              {__("Find a Member", "arraysubs")}
            </label>
            <div className="arraysubs-member-insight__search-input-wrapper">
              <input
                id="member-search"
                type="text"
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                placeholder={__(
                  "Search by name, username, or email...",
                  "arraysubs",
                )}
                className="arraysubs-member-insight__search-input"
              />
              {searching && (
                <span className="arraysubs-member-insight__searching-indicator">
                  {__("Searching...", "arraysubs")}
                </span>
              )}
            </div>

            {/* Results dropdown */}
            {searchResults.length > 0 && (
              <div className="arraysubs-member-insight__search-results">
                {searchResults.map((user) => (
                  <button
                    key={user.id}
                    type="button"
                    className="arraysubs-member-insight__search-result-item"
                    onClick={() => handleSelectUser(user)}
                  >
                    <div className="arraysubs-member-insight__result-info">
                      <span className="arraysubs-member-insight__result-name">
                        {user.display_name}
                      </span>
                      <span className="arraysubs-member-insight__result-meta">
                        {user.email} &middot; @{user.username}
                      </span>
                    </div>
                    <div className="arraysubs-member-insight__result-stats">
                      <span className="arraysubs-member-insight__result-subs">
                        {user.active_subscriptions} / {user.total_subscriptions}{" "}
                        {__("subs", "arraysubs")}
                      </span>
                    </div>
                  </button>
                ))}
              </div>
            )}
          </div>
        </div>

        {/* Member Details */}
        {selectedUser && (
          <>
            {loadingMember ? (
              <div className="arraysubs-member-insight__loading">
                <Skeleton height={120} />
                <Skeleton height={80} />
                <Skeleton height={200} />
              </div>
            ) : memberData ? (
              <MemberDetails data={memberData} onClear={handleClear} />
            ) : null}
          </>
        )}

        {/* Empty state */}
        {!selectedUser && (
          <div className="arraysubs-member-insight__empty-state">
            <User size={48} />
            <h3>{__("Member Insight Dashboard", "arraysubs")}</h3>
            <p>
              {__(
                "Search for a member above to view their complete subscription history, order history, purchased products, and account details.",
                "arraysubs",
              )}
            </p>
          </div>
        )}

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

/**
 * MemberDetails - Full member data rendering
 */
const MemberDetails = ({ data, onClear }) => {
  const { env } = window.arraySubs || {};
  const { profile, stats, subscriptions, products } = data;

  return (
    <div className="arraysubs-member-insight__details">
      {/* Profile Header Card */}
      <div className="arraysubs-member-insight__profile-card">
        <div className="arraysubs-member-insight__profile-header">
          <div className="arraysubs-member-insight__profile-avatar">
            <img
              src={profile.avatar_url}
              alt={profile.display_name}
              width={64}
              height={64}
            />
          </div>
          <div className="arraysubs-member-insight__profile-info">
            <h2 className="arraysubs-member-insight__profile-name">
              {profile.full_name || profile.display_name}
            </h2>
            <div className="arraysubs-member-insight__profile-meta">
              <span>
                <User size={14} /> @{profile.username}
              </span>
              <span>
                <Mail size={14} /> {profile.email}
              </span>
              {profile.billing?.phone && (
                <span>
                  <Phone size={14} /> {profile.billing.phone}
                </span>
              )}
              <span>
                <Calendar size={14} /> {__("Joined", "arraysubs")}{" "}
                {profile.registered_formatted}
              </span>
            </div>
            <div className="arraysubs-member-insight__profile-roles">
              {profile.roles.map((role) => (
                <span
                  key={role}
                  className="arraysubs-member-insight__role-badge"
                >
                  {role}
                </span>
              ))}
            </div>
          </div>
          <div className="arraysubs-member-insight__profile-actions">
            {profile.id > 0 &&
              (profile.login_as_user_url ? (
                <a
                  href={buildUrl(profile.login_as_user_url, {
                    back_url: window.location.href,
                  })}
                  className="button button-secondary"
                >
                  <LogIn size={14} />
                  {__("Login as Customer", "arraysubs")}
                </a>
              ) : (
                <button
                  type="button"
                  className="button button-secondary"
                  disabled
                  title={profile.login_as_user_reason || ""}
                >
                  <LogIn size={14} />
                  {__("Login as Customer", "arraysubs")}
                </button>
              ))}
            {profile.edit_url && (
              <a
                href={profile.edit_url}
                className="button button-secondary"
                target="_blank"
                rel="noopener noreferrer"
              >
                <ExternalLink size={14} />
                {__("Edit User", "arraysubs")}
              </a>
            )}
            <button
              type="button"
              className="button button-link-delete"
              onClick={onClear}
            >
              <X size={14} />
              {__("Clear", "arraysubs")}
            </button>
          </div>
        </div>
      </div>

      {/* Stats Grid */}
      <div className="arraysubs-member-insight__stats-grid">
        <StatCard
          label={__("Total Spent", "arraysubs")}
          value={stats.total_spent_formatted}
          icon={DollarSign}
          variant="primary"
        />
        <StatCard
          label={__("Total Orders", "arraysubs")}
          value={stats.total_orders}
          icon={ShoppingCart}
          variant="info"
        />
        <StatCard
          label={__("Active Subscriptions", "arraysubs")}
          value={stats.active_subscriptions}
          icon={Repeat}
          variant="success"
        />
        <StatCard
          label={__("Total Subscriptions", "arraysubs")}
          value={stats.total_subscriptions}
          icon={Package}
          variant="default"
        />
        <StatCard
          label={__("Store Credit", "arraysubs")}
          value={stats.store_credit_formatted}
          icon={CreditCard}
          variant="purple"
        />
        <StatCard
          label={__("Total Refunds", "arraysubs")}
          value={stats.total_refunds_formatted}
          icon={DollarSign}
          variant="danger"
        />
      </div>

      {/* Quick Links */}
      <div className="arraysubs-member-insight__quick-links">
        <a
          href={`${
            env?.wpAdminUrl
          }admin.php?page=wc-orders&s=${encodeURIComponent(profile.email)}`}
          className="arraysubs-member-insight__quick-link-card"
          target="_blank"
          rel="noopener noreferrer"
        >
          <div className="arraysubs-member-insight__quick-link-icon arraysubs-member-insight__quick-link-icon--orders">
            <ShoppingCart size={22} />
          </div>
          <div className="arraysubs-member-insight__quick-link-content">
            <span className="arraysubs-member-insight__quick-link-title">
              {__("View Orders", "arraysubs")}
            </span>
            <span className="arraysubs-member-insight__quick-link-desc">
              {__("View all WooCommerce orders for this customer", "arraysubs")}
            </span>
          </div>
          <ArrowRight
            size={18}
            className="arraysubs-member-insight__quick-link-arrow"
          />
        </a>
        <a
          href={`#/store-credit/${profile.id}`}
          className="arraysubs-member-insight__quick-link-card"
        >
          <div className="arraysubs-member-insight__quick-link-icon arraysubs-member-insight__quick-link-icon--credit">
            <Wallet size={22} />
          </div>
          <div className="arraysubs-member-insight__quick-link-content">
            <span className="arraysubs-member-insight__quick-link-title">
              {__("Manage Store Credit", "arraysubs")}
            </span>
            <span className="arraysubs-member-insight__quick-link-desc">
              {__("View and adjust store credit balance", "arraysubs")}
            </span>
          </div>
          <ArrowRight
            size={18}
            className="arraysubs-member-insight__quick-link-arrow"
          />
        </a>
        <a
          href={`#/subscriptions/feature-log?user_id=${profile.id}`}
          className="arraysubs-member-insight__quick-link-card"
        >
          <div className="arraysubs-member-insight__quick-link-icon arraysubs-member-insight__quick-link-icon--subscriptions">
            <Repeat size={22} />
          </div>
          <div className="arraysubs-member-insight__quick-link-content">
            <span className="arraysubs-member-insight__quick-link-title">
              {__("Show Features", "arraysubs")}
            </span>
            <span className="arraysubs-member-insight__quick-link-desc">
              {__(
                "View the customer's active feature entitlements",
                "arraysubs",
              )}
            </span>
          </div>
          <ArrowRight
            size={18}
            className="arraysubs-member-insight__quick-link-arrow"
          />
        </a>
      </div>

      {/* Subscriptions */}
      <CollapsibleSection
        title={__("Subscriptions", "arraysubs")}
        icon={Repeat}
        count={subscriptions.length}
      >
        {subscriptions.length > 0 ? (
          <table className="arraysubs-member-insight__table">
            <thead>
              <tr>
                <th>{__("ID", "arraysubs")}</th>
                <th>{__("Product", "arraysubs")}</th>
                <th>{__("Status", "arraysubs")}</th>
                <th>{__("Total", "arraysubs")}</th>
                <th>{__("Billing", "arraysubs")}</th>
                <th>{__("Next Payment", "arraysubs")}</th>
                <th>{__("Created", "arraysubs")}</th>
                <th>{__("Actions", "arraysubs")}</th>
              </tr>
            </thead>
            <tbody>
              {subscriptions.map((sub) => (
                <tr key={sub.id}>
                  <td>
                    <a href={`#/subscriptions/detail/${sub.id}`}>#{sub.id}</a>
                  </td>
                  <td>{sub.product_name}</td>
                  <td>
                    <StatusBadge status={sub.status} map={STATUS_COLORS} />
                  </td>
                  <td
                    dangerouslySetInnerHTML={{ __html: sub.total_formatted }}
                  />
                  <td>
                    {sub.billing_interval && sub.billing_period
                      ? `${__("Every", "arraysubs")} ${sub.billing_interval} ${
                          sub.billing_period
                        }`
                      : "—"}
                  </td>
                  <td>{sub.next_payment_date || "—"}</td>
                  <td>{sub.created_date_formatted}</td>
                  <td>
                    <div className="arraysubs-member-insight__table-actions">
                      <a href={`#/subscriptions/detail/${sub.id}`}>
                        {__("View", "arraysubs")}
                      </a>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        ) : (
          <p className="arraysubs-member-insight__empty-message">
            {__("No subscriptions found.", "arraysubs")}
          </p>
        )}
      </CollapsibleSection>

      {/* Non-subscription products */}
      <CollapsibleSection
        title={__("Purchased Products (Non-Subscription)", "arraysubs")}
        icon={Package}
        count={products.length}
        defaultOpen={false}
      >
        {products.length > 0 ? (
          <table className="arraysubs-member-insight__table">
            <thead>
              <tr>
                <th>{__("Product", "arraysubs")}</th>
                <th>{__("Type", "arraysubs")}</th>
                <th>{__("Qty Purchased", "arraysubs")}</th>
                <th>{__("Total Spent", "arraysubs")}</th>
              </tr>
            </thead>
            <tbody>
              {products.map((product) => (
                <tr key={product.id}>
                  <td>{product.name}</td>
                  <td>{product.type}</td>
                  <td>{product.quantity}</td>
                  <td
                    dangerouslySetInnerHTML={{
                      __html: product.total_spent_formatted,
                    }}
                  />
                </tr>
              ))}
            </tbody>
          </table>
        ) : (
          <p className="arraysubs-member-insight__empty-message">
            {__("No non-subscription products purchased.", "arraysubs")}
          </p>
        )}
      </CollapsibleSection>

      {/* Addresses */}
      <CollapsibleSection
        title={__("Addresses", "arraysubs")}
        icon={MapPin}
        defaultOpen={false}
      >
        <div className="arraysubs-member-insight__addresses-grid">
          <div className="arraysubs-member-insight__address-card">
            <h4>{__("Billing Address", "arraysubs")}</h4>
            {profile.billing?.email && (
              <p className="arraysubs-member-insight__address-contact">
                <Mail size={14} /> {profile.billing.email}
              </p>
            )}
            {profile.billing?.phone && (
              <p className="arraysubs-member-insight__address-contact">
                <Phone size={14} /> {profile.billing.phone}
              </p>
            )}
            <p className="arraysubs-member-insight__address-text">
              {formatAddress(profile.billing) ||
                __("No billing address set.", "arraysubs")}
            </p>
          </div>
          <div className="arraysubs-member-insight__address-card">
            <h4>{__("Shipping Address", "arraysubs")}</h4>
            {profile.shipping?.phone && (
              <p className="arraysubs-member-insight__address-contact">
                <Phone size={14} /> {profile.shipping.phone}
              </p>
            )}
            <p className="arraysubs-member-insight__address-text">
              {formatAddress(profile.shipping) ||
                __("No shipping address set.", "arraysubs")}
            </p>
          </div>
        </div>
      </CollapsibleSection>
    </div>
  );
};

/**
 * StatCard component
 */
const StatCard = ({ label, value, icon: Icon, variant = "default" }) => (
  <div
    className={`arraysubs-member-insight__stat-card arraysubs-member-insight__stat-card--${variant}`}
  >
    <div className="arraysubs-member-insight__stat-icon">
      <Icon size={20} />
    </div>
    <div className="arraysubs-member-insight__stat-content">
      <span
        className="arraysubs-member-insight__stat-value"
        dangerouslySetInnerHTML={{
          __html: typeof value === "string" ? value : String(value),
        }}
      />
      <span className="arraysubs-member-insight__stat-label">{label}</span>
    </div>
  </div>
);

export default ManageMembers;
