import { useState } from "react";
import {
  Loader2,
  AlertTriangle,
  Save,
  Check,
  X,
  Package,
  Plus,
  Trash2,
} from "lucide-react";
import { cn } from "../../lib/utils";
import type { User, InventoryEntry } from "../../lib/useUsers";
import {
  Field,
  NumberInput,
  StringInput,
  Toggle,
  SelectInput,
  SectionCard,
  formatBigInt,
} from "./UserFormFields";

// ---------------------------------------------------------------------------
// 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>
      <select
        value={selectedItemId}
        onChange={(e) => setSelectedItemId(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"
        )}
      >
        <option value="">Select item...</option>
        {Array.isArray(items) && items.map((item) => (
          <option key={item.id} value={item.id}>
            {item.name}
          </option>
        ))}
      </select>
      <div className="flex gap-2">
        <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(
            "flex-1 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 justify-center gap-1.5"
          )}
        >
          <Plus className="w-4 h-4" />
          Add
        </button>
      </div>
    </div>
  );
}

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

export function UserDetailPanel({
  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>
  );
}
