import { useState, useEffect } from "react";
import {
  Loader2,
  AlertTriangle,
  Save,
  Check,
  UserCircle2,
  Search,
  X,
  ChevronLeft,
  ChevronRight,
  Package,
  Plus,
  Trash2,
} from "lucide-react";
import { cn } from "../lib/utils";
import { useUsers, type User, type InventoryEntry } from "../lib/useUsers";

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

function formatNumber(num: number | string): string {
  const n = typeof num === "string" ? parseInt(num) : num;
  return n.toLocaleString();
}

function formatBigInt(value: string): string {
  try {
    const num = BigInt(value);
    return num.toLocaleString();
  } catch {
    return value;
  }
}

// ---------------------------------------------------------------------------
// Reusable field components (from Settings.tsx)
// ---------------------------------------------------------------------------

function Field({
  label,
  hint,
  children,
}: {
  label: string;
  hint?: string;
  children: React.ReactNode;
}) {
  return (
    <div className="space-y-1.5">
      <label className="block text-xs font-semibold text-text-secondary">
        {label}
      </label>
      {children}
      {hint && <p className="text-[11px] text-text-tertiary">{hint}</p>}
    </div>
  );
}

function NumberInput({
  value,
  onChange,
  min,
  max,
  step,
  className,
}: {
  value: number;
  onChange: (v: number) => void;
  min?: number;
  max?: number;
  step?: number;
  className?: string;
}) {
  return (
    <input
      type="number"
      value={value}
      onChange={(e) => onChange(Number(e.target.value))}
      min={min}
      max={max}
      step={step}
      className={cn(
        "w-full bg-input border border-border rounded-md px-3 py-2 text-sm font-mono text-foreground",
        "focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary/30",
        "transition-colors",
        className
      )}
    />
  );
}

function StringInput({
  value,
  onChange,
  placeholder,
  className,
}: {
  value: string;
  onChange: (v: string) => void;
  placeholder?: string;
  className?: string;
}) {
  return (
    <input
      type="text"
      value={value}
      onChange={(e) => onChange(e.target.value)}
      placeholder={placeholder}
      className={cn(
        "w-full bg-input border border-border rounded-md px-3 py-2 text-sm font-mono text-foreground",
        "focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary/30",
        "transition-colors",
        className
      )}
    />
  );
}

function Toggle({
  checked,
  onChange,
}: {
  checked: boolean;
  onChange: (v: boolean) => void;
}) {
  return (
    <button
      type="button"
      role="switch"
      aria-checked={checked}
      onClick={() => onChange(!checked)}
      className={cn(
        "relative inline-flex h-6 w-11 items-center rounded-full transition-colors",
        checked ? "bg-primary" : "bg-raised"
      )}
    >
      <span
        className={cn(
          "inline-block h-4 w-4 rounded-full bg-white transition-transform",
          checked ? "translate-x-6" : "translate-x-1"
        )}
      />
    </button>
  );
}

function SelectInput({
  value,
  onChange,
  options,
}: {
  value: string;
  onChange: (v: string) => void;
  options: { value: string; label: string }[];
}) {
  return (
    <select
      value={value}
      onChange={(e) => onChange(e.target.value)}
      className={cn(
        "w-full bg-input border border-border rounded-md px-3 py-2 text-sm text-foreground",
        "focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary/30",
        "transition-colors"
      )}
    >
      {options.map((o) => (
        <option key={o.value} value={o.value}>
          {o.label}
        </option>
      ))}
    </select>
  );
}

function SectionCard({
  title,
  icon: Icon,
  children,
}: {
  title: string;
  icon: React.ComponentType<{ className?: string }>;
  children: React.ReactNode;
}) {
  return (
    <div className="bg-card border border-border rounded-lg p-4">
      <div className="flex items-center gap-2 mb-4">
        <Icon className="w-4 h-4 text-primary" />
        <h3 className="text-sm font-semibold text-foreground">{title}</h3>
      </div>
      {children}
    </div>
  );
}

// ---------------------------------------------------------------------------
// SearchFilterBar Component
// ---------------------------------------------------------------------------

function SearchFilterBar({
  search,
  onSearchChange,
  classId,
  onClassChange,
  isActive,
  onActiveChange,
  sortBy,
  onSortByChange,
  sortOrder,
  onSortOrderChange,
  onClear,
  classes,
}: {
  search: string;
  onSearchChange: (v: string) => void;
  classId: string | null;
  onClassChange: (v: string | null) => void;
  isActive: boolean | null;
  onActiveChange: (v: boolean | null) => void;
  sortBy: string;
  onSortByChange: (v: string) => void;
  sortOrder: string;
  onSortOrderChange: (v: string) => void;
  onClear: () => void;
  classes: { id: string; name: string }[];
}) {
  return (
    <div className="flex flex-wrap gap-3 items-center">
      {/* Search input */}
      <div className="relative flex-1 min-w-[200px]">
        <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-text-tertiary" />
        <input
          type="text"
          value={search}
          onChange={(e) => onSearchChange(e.target.value)}
          placeholder="Search by username..."
          className={cn(
            "w-full bg-input border border-border rounded-md pl-10 pr-3 py-2 text-sm text-foreground",
            "focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary/30",
            "transition-colors"
          )}
        />
      </div>

      {/* Class filter */}
      <select
        value={classId ?? ""}
        onChange={(e) => onClassChange(e.target.value || null)}
        className={cn(
          "bg-input border border-border rounded-md px-3 py-2 text-sm text-foreground",
          "focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary/30",
          "transition-colors"
        )}
      >
        <option value="">All Classes</option>
        {Array.isArray(classes) && classes.map((c) => (
          <option key={c.id} value={c.id}>
            {c.name}
          </option>
        ))}
      </select>

      {/* Active status filter */}
      <select
        value={isActive === null ? "" : String(isActive)}
        onChange={(e) =>
          onActiveChange(e.target.value === "" ? null : e.target.value === "true")
        }
        className={cn(
          "bg-input border border-border rounded-md px-3 py-2 text-sm text-foreground",
          "focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary/30",
          "transition-colors"
        )}
      >
        <option value="">All Status</option>
        <option value="true">Active</option>
        <option value="false">Inactive</option>
      </select>

      {/* Sort by */}
      <select
        value={sortBy}
        onChange={(e) => onSortByChange(e.target.value)}
        className={cn(
          "bg-input border border-border rounded-md px-3 py-2 text-sm text-foreground",
          "focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary/30",
          "transition-colors"
        )}
      >
        <option value="balance">Sort by Balance</option>
        <option value="level">Sort by Level</option>
        <option value="xp">Sort by XP</option>
        <option value="username">Sort by Username</option>
      </select>

      {/* Sort order */}
      <button
        onClick={() => onSortOrderChange(sortOrder === "asc" ? "desc" : "asc")}
        className={cn(
          "bg-input border border-border rounded-md px-3 py-2 text-sm text-foreground",
          "hover:bg-raised transition-colors"
        )}
      >
        {sortOrder === "asc" ? "↑ Asc" : "↓ Desc"}
      </button>

      {/* Clear filters */}
      <button
        onClick={onClear}
        className={cn(
          "bg-input border border-border rounded-md px-3 py-2 text-sm text-text-secondary",
          "hover:bg-destructive hover:text-white hover:border-destructive transition-colors"
        )}
      >
        Clear
      </button>
    </div>
  );
}

// ---------------------------------------------------------------------------
// UserTable Component
// ---------------------------------------------------------------------------

function UserTable({
  users,
  loading,
  onSelectUser,
}: {
  users: User[];
  loading: boolean;
  onSelectUser: (user: User) => void;
}) {
  if (loading) {
    return (
      <div className="bg-card border border-border rounded-lg overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-raised border-b border-border">
              <tr>
                <th className="px-4 py-3 text-left text-xs font-semibold text-text-secondary">
                  Username
                </th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-text-secondary">
                  Level
                </th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-text-secondary">
                  Balance
                </th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-text-secondary">
                  Class
                </th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-text-secondary">
                  Status
                </th>
              </tr>
            </thead>
            <tbody>
              {[...Array(5)].map((_, i) => (
                <tr key={i} className="border-b border-border">
                  <td className="px-4 py-3">
                    <div className="h-4 bg-raised rounded animate-pulse w-32"></div>
                  </td>
                  <td className="px-4 py-3">
                    <div className="h-4 bg-raised rounded animate-pulse w-12"></div>
                  </td>
                  <td className="px-4 py-3">
                    <div className="h-4 bg-raised rounded animate-pulse w-24"></div>
                  </td>
                  <td className="px-4 py-3">
                    <div className="h-4 bg-raised rounded animate-pulse w-20"></div>
                  </td>
                  <td className="px-4 py-3">
                    <div className="h-4 bg-raised rounded animate-pulse w-16"></div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    );
  }

  if (users.length === 0) {
    return (
      <div className="bg-card border border-border rounded-lg p-12 text-center">
        <UserCircle2 className="w-16 h-16 mx-auto mb-4 text-text-tertiary" />
        <p className="text-lg font-semibold text-text-secondary mb-2">
          No users found
        </p>
        <p className="text-sm text-text-tertiary">
          Try adjusting your search or filter criteria
        </p>
      </div>
    );
  }

  return (
    <div className="bg-card border border-border rounded-lg overflow-hidden">
      <div className="overflow-x-auto">
        <table className="w-full">
          <thead className="bg-raised border-b border-border">
            <tr>
              <th className="px-4 py-3 text-left text-xs font-semibold text-text-secondary">
                Username
              </th>
              <th className="px-4 py-3 text-left text-xs font-semibold text-text-secondary">
                Level
              </th>
              <th className="px-4 py-3 text-left text-xs font-semibold text-text-secondary">
                Balance
              </th>
              <th className="px-4 py-3 text-left text-xs font-semibold text-text-secondary">
                XP
              </th>
              <th className="px-4 py-3 text-left text-xs font-semibold text-text-secondary">
                Class
              </th>
              <th className="px-4 py-3 text-left text-xs font-semibold text-text-secondary">
                Status
              </th>
            </tr>
          </thead>
          <tbody>
            {users.map((user) => (
              <tr
                key={user.id}
                onClick={() => onSelectUser(user)}
                className="border-b border-border hover:bg-raised cursor-pointer transition-colors"
              >
                <td className="px-4 py-3">
                  <div className="flex items-center gap-3">
                    <div className="w-8 h-8 rounded-full bg-primary/20 flex items-center justify-center">
                      <UserCircle2 className="w-5 h-5 text-primary" />
                    </div>
                    <div>
                      <p className="text-sm font-medium text-foreground">
                        {user.username}
                      </p>
                      <p className="text-xs text-text-tertiary font-mono">
                        {user.id}
                      </p>
                    </div>
                  </div>
                </td>
                <td className="px-4 py-3">
                  <span className="text-sm font-mono text-foreground">
                    {user.level}
                  </span>
                </td>
                <td className="px-4 py-3">
                  <span className="text-sm font-mono text-foreground">
                    {formatBigInt(user.balance)}
                  </span>
                </td>
                <td className="px-4 py-3">
                  <span className="text-sm font-mono text-text-secondary">
                    {formatBigInt(user.xp)}
                  </span>
                </td>
                <td className="px-4 py-3">
                  <span className="text-sm text-foreground">
                    {user.class?.name || "—"}
                  </span>
                </td>
                <td className="px-4 py-3">
                  <span
                    className={cn(
                      "inline-flex items-center px-2 py-1 rounded-full text-xs font-medium",
                      user.isActive
                        ? "bg-green-500/20 text-green-400"
                        : "bg-gray-500/20 text-gray-400"
                    )}
                  >
                    {user.isActive ? "Active" : "Inactive"}
                  </span>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// ---------------------------------------------------------------------------
// Pagination Component
// ---------------------------------------------------------------------------

function Pagination({
  currentPage,
  totalPages,
  limit,
  total,
  onPageChange,
  onLimitChange,
}: {
  currentPage: number;
  totalPages: number;
  limit: number;
  total: number;
  onPageChange: (page: number) => void;
  onLimitChange: (limit: number) => void;
}) {
  const startItem = (currentPage - 1) * limit + 1;
  const endItem = Math.min(currentPage * limit, total);

  // Calculate page numbers to show
  const getPageNumbers = () => {
    const pages: (number | string)[] = [];
    const showPages = 5;
    const halfShow = Math.floor(showPages / 2);

    let start = Math.max(1, currentPage - halfShow);
    let end = Math.min(totalPages, start + showPages - 1);

    if (end - start < showPages - 1) {
      start = Math.max(1, end - showPages + 1);
    }

    if (start > 1) {
      pages.push(1);
      if (start > 2) pages.push("...");
    }

    for (let i = start; i <= end; i++) {
      pages.push(i);
    }

    if (end < totalPages) {
      if (end < totalPages - 1) pages.push("...");
      pages.push(totalPages);
    }

    return pages;
  };

  return (
    <div className="mt-4 flex flex-wrap gap-4 items-center justify-between">
      {/* Items info */}
      <p className="text-sm text-text-secondary">
        Showing {startItem}–{endItem} of {formatNumber(total)} users
      </p>

      {/* Page controls */}
      <div className="flex items-center gap-2">
        {/* Previous button */}
        <button
          onClick={() => onPageChange(currentPage - 1)}
          disabled={currentPage === 1}
          className={cn(
            "px-3 py-2 rounded-md text-sm font-medium transition-colors",
            currentPage === 1
              ? "bg-raised text-text-tertiary cursor-not-allowed"
              : "bg-input border border-border text-foreground hover:bg-raised"
          )}
        >
          <ChevronLeft className="w-4 h-4" />
        </button>

        {/* Page numbers */}
        {getPageNumbers().map((page, i) =>
          typeof page === "number" ? (
            <button
              key={i}
              onClick={() => onPageChange(page)}
              className={cn(
                "px-3 py-2 rounded-md text-sm font-medium transition-colors min-w-[40px]",
                page === currentPage
                  ? "bg-primary text-white"
                  : "bg-input border border-border text-foreground hover:bg-raised"
              )}
            >
              {page}
            </button>
          ) : (
            <span key={i} className="px-2 text-text-tertiary">
              {page}
            </span>
          )
        )}

        {/* Next button */}
        <button
          onClick={() => onPageChange(currentPage + 1)}
          disabled={currentPage === totalPages}
          className={cn(
            "px-3 py-2 rounded-md text-sm font-medium transition-colors",
            currentPage === totalPages
              ? "bg-raised text-text-tertiary cursor-not-allowed"
              : "bg-input border border-border text-foreground hover:bg-raised"
          )}
        >
          <ChevronRight className="w-4 h-4" />
        </button>

        {/* Items per page */}
        <select
          value={limit}
          onChange={(e) => onLimitChange(Number(e.target.value))}
          className={cn(
            "ml-2 bg-input border border-border rounded-md px-3 py-2 text-sm text-foreground",
            "focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary/30",
            "transition-colors"
          )}
        >
          <option value="10">10 / page</option>
          <option value="25">25 / page</option>
          <option value="50">50 / page</option>
          <option value="100">100 / page</option>
        </select>
      </div>
    </div>
  );
}

// ---------------------------------------------------------------------------
// InventoryAddForm Component
// ---------------------------------------------------------------------------

function InventoryAddForm({
  items,
  onAdd,
}: {
  items: { id: number; name: string }[];
  onAdd: (itemId: number, quantity: string) => void;
}) {
  const [selectedItemId, setSelectedItemId] = useState<string>("");
  const [quantity, setQuantity] = useState<string>("1");

  const handleAdd = () => {
    if (!selectedItemId) return;
    onAdd(parseInt(selectedItemId), quantity);
    setSelectedItemId("");
    setQuantity("1");
  };

  return (
    <div className="space-y-3">
      <p className="text-xs font-semibold text-text-secondary">Add Item</p>
      <div className="flex gap-2">
        <select
          value={selectedItemId}
          onChange={(e) => setSelectedItemId(e.target.value)}
          className={cn(
            "flex-1 bg-input border border-border rounded-md px-3 py-2 text-sm text-foreground",
            "focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary/30",
            "transition-colors"
          )}
        >
          <option value="">Select item...</option>
          {Array.isArray(items) && items.map((item) => (
            <option key={item.id} value={item.id}>
              {item.name}
            </option>
          ))}
        </select>
        <input
          type="number"
          value={quantity}
          onChange={(e) => setQuantity(e.target.value)}
          min="1"
          placeholder="Qty"
          className={cn(
            "w-20 bg-input border border-border rounded-md px-3 py-2 text-sm font-mono text-foreground",
            "focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary/30",
            "transition-colors"
          )}
        />
        <button
          onClick={handleAdd}
          disabled={!selectedItemId}
          className={cn(
            "px-3 py-2 rounded-md text-sm font-medium transition-colors",
            "bg-primary text-white hover:bg-primary/90",
            "disabled:opacity-50 disabled:cursor-not-allowed",
            "flex items-center gap-1.5"
          )}
        >
          <Plus className="w-4 h-4" />
          Add
        </button>
      </div>
    </div>
  );
}

// ---------------------------------------------------------------------------
// DetailPanel Component
// ---------------------------------------------------------------------------

function DetailPanel({
  user,
  userDraft,
  onClose,
  onUpdateDraft,
  onSave,
  onDiscard,
  isDirty,
  saving,
  saveSuccess,
  classes,
  inventoryDraft,
  items,
  onAddItem,
  onRemoveItem,
}: {
  user: User;
  userDraft: Partial<User> | null;
  onClose: () => void;
  onUpdateDraft: (field: keyof User, value: unknown) => void;
  onSave: () => void;
  onDiscard: () => void;
  isDirty: boolean;
  saving: boolean;
  saveSuccess: boolean;
  classes: { id: string; name: string }[];
  inventoryDraft: InventoryEntry[];
  items: { id: number; name: string }[];
  onAddItem: (itemId: number, quantity: string) => void;
  onRemoveItem: (itemId: number) => void;
}) {
  if (!userDraft) return null;

  const classOptions = [
    { value: "", label: "No Class" },
    ...(Array.isArray(classes) ? classes.map((c) => ({ value: c.id, label: c.name })) : []),
  ];

  return (
    <div className="fixed inset-0 md:relative md:w-96 border-l border-border bg-card overflow-auto z-50 md:z-auto">
      <div className="p-6 space-y-6 pb-24">
        {/* Header */}
        <div className="flex items-start justify-between">
          <div className="flex-1">
            <h2 className="text-lg font-semibold text-foreground mb-1">
              {user.username}
            </h2>
            <p className="text-xs font-mono text-text-tertiary">{user.id}</p>
            <p className="text-xs text-text-tertiary mt-1">
              Joined {new Date(user.createdAt).toLocaleDateString()}
            </p>
          </div>
          <button
            onClick={onClose}
            className="text-text-tertiary hover:text-foreground transition-colors"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* User Info (Editable) */}
        <div className="space-y-4">
          <Field label="Balance" hint="User's currency balance">
            <StringInput
              value={String(userDraft.balance || "0")}
              onChange={(v) => onUpdateDraft("balance", v)}
              placeholder="0"
            />
          </Field>

          <Field label="XP" hint="User's experience points">
            <StringInput
              value={String(userDraft.xp || "0")}
              onChange={(v) => onUpdateDraft("xp", v)}
              placeholder="0"
            />
          </Field>

          <Field label="Level" hint="User's current level">
            <NumberInput
              value={userDraft.level || 1}
              onChange={(v) => onUpdateDraft("level", v)}
              min={1}
              max={100}
            />
          </Field>

          <Field label="Daily Streak" hint="Consecutive days of daily command usage">
            <NumberInput
              value={userDraft.dailyStreak || 0}
              onChange={(v) => onUpdateDraft("dailyStreak", v)}
              min={0}
            />
          </Field>

          <Field label="Class" hint="User's selected class">
            <SelectInput
              value={String(userDraft.classId || "")}
              onChange={(v) => onUpdateDraft("classId", v || null)}
              options={classOptions}
            />
          </Field>

          <Field label="Active Status" hint="Whether the user is active in the system">
            <div className="flex items-center gap-3">
              <Toggle
                checked={userDraft.isActive ?? true}
                onChange={(v) => onUpdateDraft("isActive", v)}
              />
              <span
                className={cn(
                  "text-sm font-medium",
                  userDraft.isActive ? "text-green-400" : "text-gray-400"
                )}
              >
                {userDraft.isActive ? "Active" : "Inactive"}
              </span>
            </div>
          </Field>
        </div>

        {/* Inventory Section */}
        <SectionCard title="Inventory" icon={Package}>
          {inventoryDraft.length === 0 ? (
            <p className="text-sm text-text-tertiary">No items in inventory</p>
          ) : (
            <div className="space-y-2">
              {inventoryDraft.map((entry) => (
                <div
                  key={entry.itemId}
                  className="flex items-center justify-between gap-3 p-2 bg-raised rounded-md"
                >
                  <div className="flex-1 min-w-0">
                    <p className="text-sm font-medium text-foreground truncate">
                      {entry.item?.name || `Item #${entry.itemId}`}
                    </p>
                    <p className="text-xs text-text-tertiary">
                      Quantity: {formatBigInt(entry.quantity)}
                    </p>
                  </div>
                  <button
                    onClick={() => onRemoveItem(entry.itemId)}
                    className="p-1.5 text-text-tertiary hover:text-destructive hover:bg-destructive/10 rounded transition-colors"
                    title="Remove item"
                  >
                    <Trash2 className="w-4 h-4" />
                  </button>
                </div>
              ))}
            </div>
          )}

          {/* Add Item Form */}
          <div className="mt-4 pt-4 border-t border-border">
            <InventoryAddForm items={items} onAdd={onAddItem} />
          </div>
        </SectionCard>
      </div>

      {/* Sticky footer for save/discard (only shown when dirty) */}
      {isDirty && (
        <div className="sticky bottom-0 left-0 right-0 border-t border-border bg-card p-4 space-y-3">
          <div className="flex items-center gap-2 text-amber-400">
            <AlertTriangle className="w-4 h-4" />
            <span className="text-sm font-medium">You have unsaved changes</span>
          </div>
          <div className="flex gap-2">
            <button
              onClick={onDiscard}
              disabled={saving}
              className={cn(
                "flex-1 px-4 py-2 rounded-md text-sm font-medium transition-colors",
                "bg-input border border-border text-foreground hover:bg-raised",
                saving && "opacity-50 cursor-not-allowed"
              )}
            >
              Discard
            </button>
            <button
              onClick={onSave}
              disabled={saving}
              className={cn(
                "flex-1 px-4 py-2 rounded-md text-sm font-medium transition-colors",
                "bg-primary text-white hover:bg-primary/90",
                "flex items-center justify-center gap-2",
                saving && "opacity-50 cursor-not-allowed"
              )}
            >
              {saving ? (
                <>
                  <Loader2 className="w-4 h-4 animate-spin" />
                  Saving...
                </>
              ) : saveSuccess ? (
                <>
                  <Check className="w-4 h-4" />
                  Saved!
                </>
              ) : (
                <>
                  <Save className="w-4 h-4" />
                  Save Changes
                </>
              )}
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

// ---------------------------------------------------------------------------
// Main Users Component
// ---------------------------------------------------------------------------

export default function Users() {
  const {
    users,
    total,
    currentPage,
    limit,
    setLimit,
    filters,
    setFilters,
    setSearchDebounced,
    setPage,
    selectedUser,
    selectUser,
    closeDetail,
    userDraft,
    updateDraft,
    saveDraft,
    discardDraft,
    isDirty,
    inventoryDraft,
    addInventoryItem,
    removeInventoryItem,
    classes,
    items,
    loading,
    saving,
    error,
  } = useUsers();

  const [saveSuccess, setSaveSuccess] = useState(false);
  const [searchInput, setSearchInput] = useState(filters.search);

  // Sync searchInput with filters.search when it changes externally
  useEffect(() => {
    setSearchInput(filters.search);
  }, [filters.search]);

  // Keyboard shortcuts
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === "Escape" && selectedUser) {
        if (isDirty) {
          const confirm = window.confirm(
            "You have unsaved changes. Are you sure you want to close?"
          );
          if (confirm) closeDetail();
        } else {
          closeDetail();
        }
      }
    };

    window.addEventListener("keydown", handleKeyDown);
    return () => window.removeEventListener("keydown", handleKeyDown);
  }, [selectedUser, isDirty, closeDetail]);

  const handleSave = async () => {
    const success = await saveDraft();
    if (success) {
      setSaveSuccess(true);
      setTimeout(() => setSaveSuccess(false), 2000);
    }
  };

  const handleClearFilters = () => {
    setSearchInput("");
    setFilters({
      search: "",
      classId: null,
      isActive: null,
      sortBy: "balance",
      sortOrder: "desc",
    });
  };

  const handleSearchChange = (value: string) => {
    setSearchInput(value);
    setSearchDebounced(value);
  };

  return (
    <div className="flex flex-col h-full">
      {/* Header */}
      <header className="border-b border-border p-6 space-y-4">
        <h1 className="text-2xl font-bold text-foreground">Users</h1>
        <SearchFilterBar
          search={searchInput}
          onSearchChange={handleSearchChange}
          classId={filters.classId}
          onClassChange={(v) => setFilters({ classId: v })}
          isActive={filters.isActive}
          onActiveChange={(v) => setFilters({ isActive: v })}
          sortBy={filters.sortBy}
          onSortByChange={(v) => setFilters({ sortBy: v as any })}
          sortOrder={filters.sortOrder}
          onSortOrderChange={(v) => setFilters({ sortOrder: v as any })}
          onClear={handleClearFilters}
          classes={classes}
        />
      </header>

      {/* Error banner */}
      {error && (
        <div className="mx-6 mt-4 bg-destructive/10 border border-destructive/30 rounded-lg p-4 flex items-start gap-3">
          <AlertTriangle className="w-5 h-5 text-destructive flex-shrink-0 mt-0.5" />
          <div className="flex-1">
            <p className="text-sm font-semibold text-destructive">Error</p>
            <p className="text-sm text-destructive/90">{error}</p>
          </div>
        </div>
      )}

      {/* Content area */}
      <div className="flex-1 flex overflow-hidden">
        {/* Main content */}
        <div className="flex-1 overflow-auto p-6">
          <UserTable users={users} loading={loading} onSelectUser={selectUser} />
          <Pagination
            currentPage={currentPage}
            totalPages={Math.ceil(total / limit)}
            limit={limit}
            total={total}
            onPageChange={setPage}
            onLimitChange={setLimit}
          />
        </div>

        {/* Detail panel */}
        {selectedUser && userDraft && (
          <DetailPanel
            user={selectedUser}
            userDraft={userDraft}
            onClose={closeDetail}
            onUpdateDraft={updateDraft}
            onSave={handleSave}
            onDiscard={discardDraft}
            isDirty={isDirty}
            saving={saving}
            saveSuccess={saveSuccess}
            classes={classes}
            inventoryDraft={inventoryDraft}
            items={items}
            onAddItem={(itemId, quantity) =>
              addInventoryItem(selectedUser.id, itemId, quantity)
            }
            onRemoveItem={(itemId) => removeInventoryItem(selectedUser.id, itemId)}
          />
        )}
      </div>
    </div>
  );
}
