/**
 * 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, useRef } from "react";
import { useParams, useNavigate } from "react-router-dom";
import { __, sprintf } from "@wordpress/i18n";
import {
  Search,
  User,
  Mail,
  Phone,
  MapPin,
  ShoppingCart,
  Repeat,
  CreditCard,
  Package,
  DollarSign,
  Calendar,
  ExternalLink,
  X,
  ChevronDown,
  ChevronUp,
  UserSearch,
  Wallet,
  ArrowRight,
  LogIn,
  Edit3,
  Save,
  Plus,
  Trash2,
} from "lucide-react";
import DefaultPageLayout from "@/components/DefaultPageLayout";
import { buildRestUrl, buildUrl } from "@/libs/url";
import SpinnerButton from "@libs/confirm-dialog/SpinnerButton";
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;
};

const toSelectOptions = (options = {}) =>
  Object.entries(options || {}).map(([value, label]) => ({ value, label }));

const emptyAddress = () => ({
  label: "",
  first_name: "",
  last_name: "",
  company: "",
  address_1: "",
  address_2: "",
  city: "",
  state: "",
  postcode: "",
  country: "",
  email: "",
  phone: "",
});

const normalizeAddress = (address = {}, includeEmail = false) => {
  const normalized = emptyAddress();
  Object.keys(normalized).forEach((key) => {
    if (key === "email" && !includeEmail) {
      return;
    }
    normalized[key] = address?.[key] || "";
  });

  return normalized;
};

const createProfileDraft = (profile = {}) => ({
  profile: {
    email: profile.email || "",
    first_name: profile.first_name || "",
    last_name: profile.last_name || "",
    display_name: profile.display_name || "",
  },
  billing: normalizeAddress(profile.billing, true),
  shipping: normalizeAddress(profile.shipping),
  additional_shipping_addresses: Array.isArray(
    profile.additional_shipping_addresses,
  )
    ? profile.additional_shipping_addresses.map((address) =>
        normalizeAddress(address),
      )
    : [],
});

/**
 * 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);
  const latestMemberRequest = useRef(0);

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

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

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

      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]);

  // Load member details
  const loadMemberDetails = useCallback(
    async (memberId) => {
      const numericId = parseInt(memberId, 10);
      if (numericId <= 0) {
        return;
      }

      latestMemberRequest.current = numericId;
      setLoadingMember(true);
      try {
        const response = await fetch(
          buildRestUrl(env?.apiBaseUrl, `arraysubs/v1/members/${numericId}`),
          { headers: { "X-WP-Nonce": env?.nonce } },
        );

        if (!response.ok) {
          throw new Error(__("Failed to load member data", "arraysubs"));
        }

        const data = await response.json();
        if (data.success) {
          if (latestMemberRequest.current === numericId) {
            setMemberData(data.data);
          }
        } else {
          showToast(
            data.message || __("Failed to load member data", "arraysubs"),
            "error",
          );
        }
      } catch {
        showToast(__("Failed to load member data", "arraysubs"), "error");
      } finally {
        if (latestMemberRequest.current === numericId) {
          setLoadingMember(false);
        }
      }
    },
    [env],
  );

  // Auto-load member from URL param. Treat the route as source of truth so
  // in-app hash changes cannot leave a previously selected profile visible.
  useEffect(() => {
    const numericId = parseInt(userId, 10);

    if (numericId > 0) {
      setSelectedUser({ id: numericId });
      setMemberData(null);
      loadMemberDetails(numericId);
      return;
    }

    setSelectedUser(null);
    setMemberData(null);
  }, [userId, loadMemberDetails]);

  // Select user from search
  const handleSelectUser = (user) => {
    setSelectedUser(user);
    setSearchResults([]);
    setSearchQuery("");
    navigate(`/manage-members/${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}
                onUpdated={setMemberData}
                showToast={showToast}
              />
            ) : 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, onUpdated, showToast }) => {
  const { env } = window.arraySubs || {};
  const { profile, stats = {}, subscriptions = [], products = [] } = data;
  const [editing, setEditing] = useState(false);
  const [saving, setSaving] = useState(false);
  const [draft, setDraft] = useState(() => createProfileDraft(profile));
  const parsedActiveSubscriptionCount = Number(stats.active_subscriptions);
  const activeSubscriptionCount = Number.isFinite(
    parsedActiveSubscriptionCount,
  )
    ? parsedActiveSubscriptionCount
    : subscriptions.filter((subscription) => {
        return subscription.status === "arraysubs-active";
      }).length;

  useEffect(() => {
    setDraft(createProfileDraft(profile));
  }, [profile]);

  const countryOptions = toSelectOptions(env?.countries);
  const shippingCountryOptions = toSelectOptions(
    env?.shippingCountries && Object.keys(env.shippingCountries).length
      ? env.shippingCountries
      : env?.countries,
  );

  const updateDraft = (section, field, value) => {
    setDraft((current) => ({
      ...current,
      [section]: {
        ...current[section],
        [field]: value,
      },
    }));
  };

  const updateAdditionalAddress = (index, field, value) => {
    setDraft((current) => {
      const next = [...current.additional_shipping_addresses];
      next[index] = {
        ...next[index],
        [field]: value,
        ...(field === "country" ? { state: "" } : {}),
      };
      return {
        ...current,
        additional_shipping_addresses: next,
      };
    });
  };

  const handleSave = async () => {
    setSaving(true);
    try {
      const response = await fetch(
        buildRestUrl(env?.apiBaseUrl, `arraysubs/v1/members/${profile.id}`),
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            "X-WP-Nonce": env?.nonce,
          },
          body: JSON.stringify(draft),
        },
      );

      const result = await response.json();
      if (!response.ok || !result.success) {
        throw new Error(
          result.message || __("Failed to update member details", "arraysubs"),
        );
      }

      onUpdated(result.data);
      setEditing(false);
      showToast(__("Member details updated.", "arraysubs"), "success");
    } catch (error) {
      showToast(error.message, "error");
    } finally {
      setSaving(false);
    }
  };

  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} />{" "}
                <a href={`mailto:${profile.email}`}>{profile.email}</a>
              </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">
            {editing ? (
              <>
                <SpinnerButton
                  type="button"
                  className="button button-primary"
                  onClick={handleSave}
                  loading={saving}
                  loadingText={__("Saving...", "arraysubs")}
                >
                  <Save size={14} />
                  {__("Save Details", "arraysubs")}
                </SpinnerButton>
                <button
                  type="button"
                  className="button button-secondary"
                  onClick={() => {
                    setDraft(createProfileDraft(profile));
                    setEditing(false);
                  }}
                  disabled={saving}
                >
                  <X size={14} />
                  {__("Cancel Edit", "arraysubs")}
                </button>
              </>
            ) : (
              <button
                type="button"
                className="button button-secondary"
                onClick={() => setEditing(true)}
              >
                <Edit3 size={14} />
                {__("Edit Details", "arraysubs")}
              </button>
            )}
            {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>

      {editing && (
        <MemberProfileEditPanel
          draft={draft}
          updateDraft={updateDraft}
          updateAdditionalAddress={updateAdditionalAddress}
          setDraft={setDraft}
          countryOptions={countryOptions}
          shippingCountryOptions={shippingCountryOptions}
          states={env?.states || {}}
          saving={saving}
        />
      )}

      {/* 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={activeSubscriptionCount}
          icon={Repeat}
          variant="success"
        />
        <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={activeSubscriptionCount}
      >
        {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>
          {Array.isArray(profile.additional_shipping_addresses) &&
            profile.additional_shipping_addresses.map((address, index) => (
              <div
                className="arraysubs-member-insight__address-card"
                key={`shipping-address-${index}`}
              >
                <h4>
                  {address.label ||
                    sprintf(
                      __("Shipping Address %d", "arraysubs"),
                      index + 2,
                    )}
                </h4>
                {address.phone && (
                  <p className="arraysubs-member-insight__address-contact">
                    <Phone size={14} /> {address.phone}
                  </p>
                )}
                <p className="arraysubs-member-insight__address-text">
                  {formatAddress(address) ||
                    __("No shipping address set.", "arraysubs")}
                </p>
              </div>
            ))}
        </div>
      </CollapsibleSection>
    </div>
  );
};

/**
 * MemberProfileEditPanel component
 */
const MemberProfileEditPanel = ({
  draft,
  updateDraft,
  updateAdditionalAddress,
  setDraft,
  countryOptions,
  shippingCountryOptions,
  states,
  saving,
}) => {
  const addAdditionalAddress = () => {
    setDraft((current) => ({
      ...current,
      additional_shipping_addresses: [
        ...current.additional_shipping_addresses,
        emptyAddress(),
      ],
    }));
  };

  const removeAdditionalAddress = (index) => {
    setDraft((current) => ({
      ...current,
      additional_shipping_addresses:
        current.additional_shipping_addresses.filter((_, i) => i !== index),
    }));
  };

  return (
    <div className="arraysubs-member-insight__edit-panel">
      <div className="arraysubs-member-insight__edit-section">
        <h3>{__("Account", "arraysubs")}</h3>
        <div className="arraysubs-member-insight__edit-grid">
          <FieldInput
            label={__("First Name", "arraysubs")}
            value={draft.profile.first_name}
            onChange={(value) => updateDraft("profile", "first_name", value)}
            disabled={saving}
          />
          <FieldInput
            label={__("Last Name", "arraysubs")}
            value={draft.profile.last_name}
            onChange={(value) => updateDraft("profile", "last_name", value)}
            disabled={saving}
          />
          <FieldInput
            label={__("Display Name", "arraysubs")}
            value={draft.profile.display_name}
            onChange={(value) => updateDraft("profile", "display_name", value)}
            disabled={saving}
          />
          <FieldInput
            type="email"
            label={__("Account Email", "arraysubs")}
            value={draft.profile.email}
            onChange={(value) => updateDraft("profile", "email", value)}
            disabled={saving}
          />
        </div>
      </div>

      <div className="arraysubs-member-insight__edit-section">
        <h3>{__("Billing Address", "arraysubs")}</h3>
        <AddressEditor
          address={draft.billing}
          onChange={(field, value) => updateDraft("billing", field, value)}
          countries={countryOptions}
          states={states}
          includeEmail
          disabled={saving}
        />
      </div>

      <div className="arraysubs-member-insight__edit-section">
        <h3>{__("Primary Shipping Address", "arraysubs")}</h3>
        <AddressEditor
          address={draft.shipping}
          onChange={(field, value) => updateDraft("shipping", field, value)}
          countries={shippingCountryOptions}
          states={states}
          disabled={saving}
        />
      </div>

      <div className="arraysubs-member-insight__edit-section">
        <div className="arraysubs-member-insight__edit-section-header">
          <h3>{__("Additional Shipping Addresses", "arraysubs")}</h3>
          <button
            type="button"
            className="button button-secondary"
            onClick={addAdditionalAddress}
            disabled={saving}
          >
            <Plus size={14} />
            {__("Add Address", "arraysubs")}
          </button>
        </div>

        {draft.additional_shipping_addresses.length === 0 ? (
          <p className="arraysubs-member-insight__empty-message">
            {__("No additional shipping addresses.", "arraysubs")}
          </p>
        ) : (
          draft.additional_shipping_addresses.map((address, index) => (
            <div
              className="arraysubs-member-insight__additional-address"
              key={`additional-shipping-${index}`}
            >
              <div className="arraysubs-member-insight__additional-address-header">
                <FieldInput
                  label={__("Address Label", "arraysubs")}
                  value={address.label}
                  onChange={(value) =>
                    updateAdditionalAddress(index, "label", value)
                  }
                  disabled={saving}
                />
                <button
                  type="button"
                  className="button button-link-delete"
                  onClick={() => removeAdditionalAddress(index)}
                  disabled={saving}
                >
                  <Trash2 size={14} />
                  {__("Remove", "arraysubs")}
                </button>
              </div>
              <AddressEditor
                address={address}
                onChange={(field, value) =>
                  updateAdditionalAddress(index, field, value)
                }
                countries={shippingCountryOptions}
                states={states}
                disabled={saving}
              />
            </div>
          ))
        )}
      </div>
    </div>
  );
};

/**
 * AddressEditor component
 */
const AddressEditor = ({
  address,
  onChange,
  countries,
  states,
  includeEmail = false,
  disabled = false,
}) => {
  const stateOptions = toSelectOptions(states?.[address.country] || {});

  return (
    <div className="arraysubs-member-insight__edit-grid">
      <FieldInput
        label={__("First Name", "arraysubs")}
        value={address.first_name}
        onChange={(value) => onChange("first_name", value)}
        disabled={disabled}
      />
      <FieldInput
        label={__("Last Name", "arraysubs")}
        value={address.last_name}
        onChange={(value) => onChange("last_name", value)}
        disabled={disabled}
      />
      <FieldInput
        label={__("Company", "arraysubs")}
        value={address.company}
        onChange={(value) => onChange("company", value)}
        disabled={disabled}
      />
      {includeEmail && (
        <FieldInput
          type="email"
          label={__("Billing Email", "arraysubs")}
          value={address.email}
          onChange={(value) => onChange("email", value)}
          disabled={disabled}
        />
      )}
      <FieldInput
        label={__("Address Line 1", "arraysubs")}
        value={address.address_1}
        onChange={(value) => onChange("address_1", value)}
        disabled={disabled}
      />
      <FieldInput
        label={__("Address Line 2", "arraysubs")}
        value={address.address_2}
        onChange={(value) => onChange("address_2", value)}
        disabled={disabled}
      />
      <FieldInput
        label={__("City", "arraysubs")}
        value={address.city}
        onChange={(value) => onChange("city", value)}
        disabled={disabled}
      />
      <label className="arraysubs-member-insight__field">
        <span>{__("Country", "arraysubs")}</span>
        <select
          value={address.country}
          onChange={(event) => {
            onChange("country", event.target.value);
            onChange("state", "");
          }}
          disabled={disabled}
        >
          <option value="">{__("Select a country", "arraysubs")}</option>
          {countries.map((country) => (
            <option key={country.value} value={country.value}>
              {country.label}
            </option>
          ))}
        </select>
      </label>
      <label className="arraysubs-member-insight__field">
        <span>{__("State / Province", "arraysubs")}</span>
        {stateOptions.length > 0 ? (
          <select
            value={address.state}
            onChange={(event) => onChange("state", event.target.value)}
            disabled={disabled}
          >
            <option value="">{__("Select a state", "arraysubs")}</option>
            {stateOptions.map((state) => (
              <option key={state.value} value={state.value}>
                {state.label}
              </option>
            ))}
          </select>
        ) : (
          <input
            type="text"
            value={address.state}
            onChange={(event) => onChange("state", event.target.value)}
            disabled={disabled}
          />
        )}
      </label>
      <FieldInput
        label={__("Postcode / ZIP", "arraysubs")}
        value={address.postcode}
        onChange={(value) => onChange("postcode", value)}
        disabled={disabled}
      />
      <FieldInput
        label={__("Phone", "arraysubs")}
        value={address.phone}
        onChange={(value) => onChange("phone", value)}
        disabled={disabled}
      />
    </div>
  );
};

/**
 * FieldInput component
 */
const FieldInput = ({
  label,
  value,
  onChange,
  type = "text",
  disabled = false,
}) => (
  <label className="arraysubs-member-insight__field">
    <span>{label}</span>
    <input
      type={type}
      value={value || ""}
      onChange={(event) => onChange(event.target.value)}
      disabled={disabled}
    />
  </label>
);

/**
 * 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;
