import {
  Package,
  Zap,
  Shield,
  MessageSquare,
  TrendingUp,
  Palette,
  CircleDollarSign,
  Gift,
} from "lucide-react";
import { cn } from "../../lib/utils";

// ===== Types =====

export type ItemType = "MATERIAL" | "CONSUMABLE" | "EQUIPMENT" | "QUEST";
export type ItemRarity = "C" | "R" | "SR" | "SSR";
export type EffectKind =
  | "ADD_XP"
  | "ADD_BALANCE"
  | "REPLY_MESSAGE"
  | "XP_BOOST"
  | "TEMP_ROLE"
  | "COLOR_ROLE"
  | "LOOTBOX";

export type LootEntryType = "NOTHING" | "CURRENCY" | "XP" | "ITEM";

export interface LootPoolEntry {
  _id: string;
  type: LootEntryType;
  weight: string;
  amountMode: "fixed" | "range";
  amount: string;
  minAmount: string;
  maxAmount: string;
  itemId: string;
  selectedItemName: string;
  selectedItemRarity: string;
  message: string;
}

export interface EffectDraft {
  _id: string;
  kind: EffectKind;
  amount: string;
  multiplier: string;
  durationSeconds: string;
  roleId: string;
  message: string;
  pool: LootPoolEntry[];
}

export interface Draft {
  name: string;
  description: string;
  type: ItemType;
  rarity: ItemRarity;
  price: string;
  consume: boolean;
  effects: EffectDraft[];
}

// ===== Full item shape returned by GET /api/items/:id =====

export interface LootPayloadEntry {
  type: LootEntryType;
  weight: number;
  amount?: number;
  minAmount?: number;
  maxAmount?: number;
  itemId?: number;
  message?: string;
}

export type StoredEffect =
  | { type: "ADD_XP"; amount: number }
  | { type: "ADD_BALANCE"; amount: number }
  | { type: "REPLY_MESSAGE"; message: string }
  | { type: "XP_BOOST"; multiplier: number; durationSeconds?: number }
  | { type: "TEMP_ROLE"; roleId: string; durationSeconds?: number }
  | { type: "COLOR_ROLE"; roleId: string }
  | { type: "LOOTBOX"; pool: LootPayloadEntry[] };

export interface FullItem {
  id: number;
  name: string;
  description: string | null;
  type: ItemType;
  rarity: ItemRarity;
  price: string | null;
  iconUrl: string;
  imageUrl: string;
  usageData: { consume: boolean; effects: StoredEffect[] } | null;
}

// ===== Constants =====

export const TYPE_META: Record<
  ItemType,
  { label: string; icon: React.ComponentType<{ className?: string }> }
> = {
  MATERIAL: { label: "Material", icon: Package },
  CONSUMABLE: { label: "Consumable", icon: Zap },
  EQUIPMENT: { label: "Equipment", icon: Shield },
  QUEST: { label: "Quest", icon: MessageSquare },
};

export const RARITY_META: Record<
  ItemRarity,
  {
    label: string;
    bg: string;
    text: string;
    activeBorder: string;
    badgeBg: string;
  }
> = {
  C: {
    label: "Common",
    bg: "bg-gray-500/15",
    text: "text-gray-300",
    activeBorder: "border-gray-500",
    badgeBg: "bg-gray-500/20",
  },
  R: {
    label: "Rare",
    bg: "bg-blue-500/15",
    text: "text-blue-300",
    activeBorder: "border-blue-500",
    badgeBg: "bg-blue-500/20",
  },
  SR: {
    label: "Super Rare",
    bg: "bg-purple-500/15",
    text: "text-purple-300",
    activeBorder: "border-purple-500",
    badgeBg: "bg-purple-500/20",
  },
  SSR: {
    label: "SSR",
    bg: "bg-amber-500/15",
    text: "text-amber-300",
    activeBorder: "border-amber-500",
    badgeBg: "bg-amber-500/20",
  },
};

export const RARITY_BADGE: Record<string, string> = {
  C: "bg-gray-500/20 text-gray-400",
  R: "bg-blue-500/20 text-blue-400",
  SR: "bg-purple-500/20 text-purple-400",
  SSR: "bg-amber-500/20 text-amber-400",
};

export const EFFECT_META: Record<
  EffectKind,
  { label: string; icon: React.ComponentType<{ className?: string }> }
> = {
  ADD_XP: { label: "Add XP", icon: Zap },
  ADD_BALANCE: { label: "Add Balance", icon: CircleDollarSign },
  REPLY_MESSAGE: { label: "Reply Message", icon: MessageSquare },
  XP_BOOST: { label: "XP Boost", icon: TrendingUp },
  TEMP_ROLE: { label: "Temporary Role", icon: Shield },
  COLOR_ROLE: { label: "Color Role", icon: Palette },
  LOOTBOX: { label: "Lootbox", icon: Gift },
};

export const LOOT_TYPE_META: Record<
  LootEntryType,
  { label: string; barColor: string; textColor: string }
> = {
  NOTHING: {
    label: "Nothing",
    barColor: "bg-text-disabled",
    textColor: "text-text-tertiary",
  },
  CURRENCY: {
    label: "Currency",
    barColor: "bg-gold",
    textColor: "text-gold",
  },
  XP: {
    label: "XP",
    barColor: "bg-blue-400",
    textColor: "text-blue-400",
  },
  ITEM: {
    label: "Item",
    barColor: "bg-purple-400",
    textColor: "text-purple-400",
  },
};

// ===== Helpers =====

export function uid() {
  return Math.random().toString(36).slice(2);
}

export function makeLootEntry(): LootPoolEntry {
  return {
    _id: uid(),
    type: "CURRENCY",
    weight: "1",
    amountMode: "fixed",
    amount: "",
    minAmount: "",
    maxAmount: "",
    itemId: "",
    selectedItemName: "",
    selectedItemRarity: "",
    message: "",
  };
}

export function makeEffect(kind: EffectKind): EffectDraft {
  return {
    _id: uid(),
    kind,
    amount: "",
    multiplier: "",
    durationSeconds: "",
    roleId: "",
    message: "",
    pool: [],
  };
}

export function defaultDraft(): Draft {
  return {
    name: "",
    description: "",
    type: "MATERIAL",
    rarity: "C",
    price: "",
    consume: false,
    effects: [],
  };
}

export function draftFromItem(item: FullItem): Draft {
  const effects: EffectDraft[] = (item.usageData?.effects ?? []).map((eff) => {
    const base = makeEffect(eff.type as EffectKind);
    switch (eff.type) {
      case "ADD_XP":
      case "ADD_BALANCE":
        return { ...base, amount: String(eff.amount) };
      case "REPLY_MESSAGE":
        return { ...base, message: eff.message };
      case "XP_BOOST":
        return {
          ...base,
          multiplier: String(eff.multiplier),
          durationSeconds: String(eff.durationSeconds ?? ""),
        };
      case "TEMP_ROLE":
        return {
          ...base,
          roleId: eff.roleId,
          durationSeconds: String(eff.durationSeconds ?? ""),
        };
      case "COLOR_ROLE":
        return { ...base, roleId: eff.roleId };
      case "LOOTBOX":
        return {
          ...base,
          pool: eff.pool.map((entry) => ({
            _id: uid(),
            type: entry.type,
            weight: String(entry.weight),
            amountMode:
              entry.minAmount !== undefined || entry.maxAmount !== undefined
                ? ("range" as const)
                : ("fixed" as const),
            amount: String(entry.amount ?? ""),
            minAmount: String(entry.minAmount ?? ""),
            maxAmount: String(entry.maxAmount ?? ""),
            itemId: String(entry.itemId ?? ""),
            selectedItemName: "",
            selectedItemRarity: "",
            message: entry.message ?? "",
          })),
        };
      default:
        return base;
    }
  });

  return {
    name: item.name,
    description: item.description ?? "",
    type: item.type,
    rarity: item.rarity,
    price: item.price ? String(parseInt(item.price)) : "",
    consume: item.usageData?.consume ?? false,
    effects,
  };
}

export const inputCls = 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",
  "placeholder:text-text-tertiary transition-colors"
);
