import { Trash2 } from "lucide-react";
import { cn } from "../../lib/utils";
import {
  type LootPoolEntry,
  type LootEntryType,
  LOOT_TYPE_META,
  inputCls,
} from "./ItemStudioTypes";
import { Field } from "./ItemStudioShared";
import { ItemSearchPicker } from "./ItemSearchPicker";

// ===== Loot Pool Entry Editor =====

export function LootPoolEntryEditor({
  entry,
  totalWeight,
  onChange,
  onRemove,
}: {
  entry: LootPoolEntry;
  totalWeight: number;
  onChange: (updated: LootPoolEntry) => void;
  onRemove: () => void;
}) {
  const upd = (fields: Partial<LootPoolEntry>) =>
    onChange({ ...entry, ...fields });

  const weight = Number(entry.weight || 0);
  const pct =
    totalWeight > 0 ? ((weight / totalWeight) * 100).toFixed(1) : "0.0";
  const meta = LOOT_TYPE_META[entry.type];

  const resetAmounts = {
    amount: "",
    minAmount: "",
    maxAmount: "",
    itemId: "",
    selectedItemName: "",
    selectedItemRarity: "",
  };

  return (
    <div className="bg-raised/30 border border-border rounded-lg p-3 space-y-3">
      {/* Header row: type tabs + weight input + percentage + remove */}
      <div className="flex items-center gap-2 flex-wrap">
        <div className="flex gap-1 flex-1 flex-wrap">
          {(Object.keys(LOOT_TYPE_META) as LootEntryType[]).map((t) => (
            <button
              key={t}
              onClick={() => upd({ type: t, ...resetAmounts })}
              className={cn(
                "px-2 py-1 rounded text-xs font-medium transition-colors border",
                entry.type === t
                  ? "bg-primary/15 border-primary text-primary"
                  : "bg-input border-border text-text-tertiary hover:text-foreground"
              )}
            >
              {LOOT_TYPE_META[t].label}
            </button>
          ))}
        </div>
        <div className="flex items-center gap-1.5 shrink-0">
          <label className="text-xs text-text-tertiary">Weight</label>
          <input
            type="number"
            min="1"
            value={entry.weight}
            onChange={(e) => upd({ weight: e.target.value })}
            className={cn(
              "w-14 bg-input border border-border rounded-md px-2 py-1 text-xs text-foreground text-center",
              "focus:outline-none focus:border-primary transition-colors"
            )}
          />
          <span className={cn("text-xs font-semibold w-12 text-right", meta.textColor)}>
            {pct}%
          </span>
        </div>
        <button
          onClick={onRemove}
          className="p-1 rounded text-text-tertiary hover:text-destructive hover:bg-destructive/10 transition-colors shrink-0"
          title="Remove entry"
        >
          <Trash2 className="w-3.5 h-3.5" />
        </button>
      </div>

      {/* NOTHING */}
      {entry.type === "NOTHING" && (
        <Field label="Message (optional)">
          <input
            type="text"
            value={entry.message}
            onChange={(e) => upd({ message: e.target.value })}
            placeholder="You found nothing inside..."
            className={inputCls}
          />
        </Field>
      )}

      {/* CURRENCY / XP */}
      {(entry.type === "CURRENCY" || entry.type === "XP") && (
        <div className="space-y-3">
          <div className="flex gap-1.5">
            {(["fixed", "range"] as const).map((mode) => (
              <button
                key={mode}
                onClick={() => upd({ amountMode: mode })}
                className={cn(
                  "px-2.5 py-1 rounded text-xs font-medium border transition-colors",
                  entry.amountMode === mode
                    ? "bg-primary/15 border-primary text-primary"
                    : "bg-input border-border text-text-tertiary hover:text-foreground"
                )}
              >
                {mode === "fixed" ? "Fixed" : "Random Range"}
              </button>
            ))}
          </div>

          {entry.amountMode === "fixed" ? (
            <Field
              label={
                entry.type === "CURRENCY" ? "Coins Amount" : "XP Amount"
              }
            >
              <input
                type="number"
                min="1"
                value={entry.amount}
                onChange={(e) => upd({ amount: e.target.value })}
                placeholder="e.g. 100"
                className={inputCls}
              />
            </Field>
          ) : (
            <div className="grid grid-cols-2 gap-3">
              <Field label="Min">
                <input
                  type="number"
                  min="0"
                  value={entry.minAmount}
                  onChange={(e) => upd({ minAmount: e.target.value })}
                  placeholder="e.g. 50"
                  className={inputCls}
                />
              </Field>
              <Field label="Max">
                <input
                  type="number"
                  min="0"
                  value={entry.maxAmount}
                  onChange={(e) => upd({ maxAmount: e.target.value })}
                  placeholder="e.g. 200"
                  className={inputCls}
                />
              </Field>
            </div>
          )}

          <Field label="Message (optional)">
            <input
              type="text"
              value={entry.message}
              onChange={(e) => upd({ message: e.target.value })}
              placeholder={
                entry.type === "CURRENCY"
                  ? "You received {amount} coins!"
                  : "You gained {amount} XP!"
              }
              className={inputCls}
            />
          </Field>
        </div>
      )}

      {/* ITEM */}
      {entry.type === "ITEM" && (
        <div className="space-y-3">
          <Field label="Item to Award">
            <ItemSearchPicker
              value={
                entry.itemId && entry.selectedItemName
                  ? {
                      id: Number(entry.itemId),
                      name: entry.selectedItemName,
                      rarity: entry.selectedItemRarity,
                    }
                  : null
              }
              onChange={(item) =>
                upd({
                  itemId: item ? String(item.id) : "",
                  selectedItemName: item?.name ?? "",
                  selectedItemRarity: item?.rarity ?? "",
                })
              }
            />
          </Field>
          <Field label="Quantity (optional, defaults to 1)">
            <input
              type="number"
              min="1"
              value={entry.amount}
              onChange={(e) => upd({ amount: e.target.value })}
              placeholder="1"
              className={inputCls}
            />
          </Field>
          <Field label="Message (optional)">
            <input
              type="text"
              value={entry.message}
              onChange={(e) => upd({ message: e.target.value })}
              placeholder="You found a rare item!"
              className={inputCls}
            />
          </Field>
        </div>
      )}
    </div>
  );
}
