import { Plus } from "lucide-react";
import { cn } from "../../lib/utils";
import {
  type LootPoolEntry,
  type LootEntryType,
  LOOT_TYPE_META,
  makeLootEntry,
} from "./ItemStudioTypes";
import { LootPoolEntryEditor } from "./LootPoolEntryEditor";

// ===== Lootbox Pool Builder =====

export function LootboxEditor({
  pool,
  onChange,
}: {
  pool: LootPoolEntry[];
  onChange: (pool: LootPoolEntry[]) => void;
}) {
  const totalWeight = pool.reduce((sum, e) => sum + Number(e.weight || 0), 0);

  const addEntry = () => onChange([...pool, makeLootEntry()]);
  const updateEntry = (i: number, updated: LootPoolEntry) => {
    const next = [...pool];
    next[i] = updated;
    onChange(next);
  };
  const removeEntry = (i: number) =>
    onChange(pool.filter((_, idx) => idx !== i));

  return (
    <div className="space-y-3 pt-1">
      {/* Summary bar */}
      {pool.length > 0 && (
        <div className="space-y-1.5">
          <div className="flex items-center justify-between">
            <span className="text-xs text-text-tertiary">
              {pool.length} entr{pool.length === 1 ? "y" : "ies"} · total
              weight {totalWeight}
            </span>
            <div className="flex gap-2">
              {(Object.keys(LOOT_TYPE_META) as LootEntryType[]).map((t) => {
                const count = pool.filter((e) => e.type === t).length;
                if (!count) return null;
                return (
                  <span
                    key={t}
                    className={cn(
                      "text-xs",
                      LOOT_TYPE_META[t].textColor
                    )}
                  >
                    {LOOT_TYPE_META[t].label} ×{count}
                  </span>
                );
              })}
            </div>
          </div>
          {/* Stacked probability bar */}
          <div className="flex h-2 w-full rounded-full overflow-hidden gap-px bg-raised">
            {pool.map((e) => {
              const w = Number(e.weight || 0);
              const pct = totalWeight > 0 ? (w / totalWeight) * 100 : 0;
              return (
                <div
                  key={e._id}
                  style={{ width: `${pct}%` }}
                  className={cn(
                    "transition-all duration-200",
                    LOOT_TYPE_META[e.type].barColor
                  )}
                  title={`${LOOT_TYPE_META[e.type].label}: ${pct.toFixed(1)}%`}
                />
              );
            })}
          </div>
        </div>
      )}

      {/* Pool entries */}
      {pool.map((entry, i) => (
        <LootPoolEntryEditor
          key={entry._id}
          entry={entry}
          totalWeight={totalWeight}
          onChange={(updated) => updateEntry(i, updated)}
          onRemove={() => removeEntry(i)}
        />
      ))}

      {/* Empty hint */}
      {pool.length === 0 && (
        <p className="text-xs text-text-tertiary text-center py-2">
          Add pool entries — each has a type, weight, and reward amount.
        </p>
      )}

      {/* Add entry */}
      <button
        onClick={addEntry}
        className={cn(
          "w-full flex items-center justify-center gap-2 py-2 rounded-lg border border-dashed text-xs",
          "border-border text-text-tertiary hover:border-amber-500/50 hover:text-amber-400 transition-colors"
        )}
      >
        <Plus className="w-3.5 h-3.5" />
        Add Pool Entry
      </button>
    </div>
  );
}
