import { useState } from "react";
import { invoke } from "@tauri-apps/api/core";
import { parseLlmJson, flattenValue } from "../lib/llm-parse";
import { GeneratedImage } from "./GeneratedImage";
import { addToLore } from "../lib/lore";
import { useToast } from "./Toast";
import { addGeneration, extractTitle, type Generation } from "../lib/generations";
import { usePrefillEffect } from "../lib/usePrefill";

interface ItemMechanics {
  attunement: string; // "none", "yes", or a condition string
  charges: string;    // "0" or "N (regen 1d6 per dawn)"
  value: string;      // "500 gp"
  weight: string;    // "2 lbs"
  effect: string;    // one-line effect description
}

interface ItemResponse {
  name: string;
  rarity: string;
  type: string;
  description: string;
  mechanical: string | Record<string, unknown> | ItemMechanics;
  lore: string;
}

const RARITIES = ["Common", "Uncommon", "Rare", "Very Rare", "Legendary", "Artifact"];
const TYPES = ["Weapon", "Armor", "Potion", "Scroll", "Wondrous Item", "Ring", "Wand", "Staff"];

interface Props {
  prefill?: Generation | null;
  onPrefillConsumed?: () => void;
}

export function ItemForge({ prefill, onPrefillConsumed }: Props = {}) {
  const [rarity, setRarity] = useState("Rare");
  const [itemType, setItemType] = useState("Wondrous Item");
  const [prompt, setPrompt] = useState("");
  const [item, setItem] = useState<ItemResponse | null>(null);
  const [rawResponse, setRawResponse] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const [artNonce, setArtNonce] = useState(0);
  const { addToast } = useToast();

  usePrefillEffect(prefill ?? null, "item", () => onPrefillConsumed?.(), (g) => {
    const parsed = parseLlmJson<ItemResponse>(g.data);
    if (parsed) {
      setItem(parsed);
      setRarity(parsed.rarity || "Rare");
      setItemType(parsed.type || "Wondrous Item");
      addToast(`Loaded "${g.title}" from history`, "info");
    }
  });

  // ponytail: FLUX.2 renders readable text, so the item name is painted in-image.
  const artPrompt = item ? `fantasy product shot of a ${item.rarity || rarity} ${item.type || itemType} named "${item.name || "magic item"}", ${flattenValue(item.description)}, dramatic side lighting, dark velvet background, 1024x1024` : null;

  async function generate() {
    setLoading(true);
    setItem(null);
    setRawResponse(null);
    try {
      const result = await invoke<string>("generate", {
        req: {
          prompt: `Create a D&D 5e magic item with the following specifications:
Rarity: ${rarity}
Type: ${itemType}
${prompt ? `Additional details: ${prompt}` : ""}

IMPORTANT: Return ONLY a raw JSON object, with NO markdown fences, NO code blocks, NO extra text.
The response must start with { and end with }.

The JSON must have exactly these keys:
- "name": the item's evocative name (string)
- "rarity": "${rarity}" (string)
- "type": "${itemType}" (string)
- "description": a vivid 2-3 sentence physical description (string)
- "mechanical": an object with keys attunement (string: "none", "yes", or a condition), charges (string), value (string), weight (string), and effect (a one-line string describing the item's mechanical effect)
- "lore": a 1-2 sentence piece of lore or history (string)`,
          system: "You are a creative D&D item designer. You MUST respond with ONLY valid JSON. No markdown fences, no code blocks, no explanation. Just the JSON object.",
          temperature: 0.85,
          max_tokens: 600,
          ragQuery: `${rarity} ${itemType} ${prompt}`,
        },
      });

      setRawResponse(result);
      const parsed = parseLlmJson<ItemResponse>(result);

      if (parsed) {
        setItem(parsed);
        addToast("Item forged", "success");
        const title = extractTitle("item", result, `${parsed.rarity ?? rarity} ${parsed.type ?? itemType}`);
        const source = `${parsed.rarity || rarity} ${parsed.type || itemType}${prompt ? ` — ${prompt}` : ""}`;
        void addGeneration({ kind: "item", title, data: result, source });
        void addToLore(
          `Item: ${parsed.name || itemType}`,
          `${parsed.name || "Magic item"} — ${parsed.rarity || rarity} ${parsed.type || itemType}. ${flattenValue(parsed.description)}\nMechanics: ${flattenValue(parsed.mechanical)}\nLore: ${flattenValue(parsed.lore)}`,
        );
      } else {
        addToast("LLM returned an unparseable response", "error");
      }
    } catch (e) {
      addToast(`Item generation failed: ${e}`, "error");
    }
    setLoading(false);
  }

  const rarityColor: Record<string, string> = {
    Common: "var(--color-text-secondary)",
    Uncommon: "#1eff00",
    Rare: "#0070dd",
    "Very Rare": "#a335ee",
    Legendary: "#ff8000",
    Artifact: "#e6cc80",
  };

  const mechanicalText = item ? flattenValue(item.mechanical) : "";
  // ponytail: structured mechanics if the LLM returned the object form; fall
  // back to a paragraph string for older generations.
  const mech = item?.mechanical;
  const isStructured =
    typeof mech === "object" && mech !== null && "attunement" in mech && "effect" in mech;
  const structured = isStructured ? (mech as ItemMechanics) : null;
  const hasParseError = !item && rawResponse;

  // ponytail: one-click "surprise me" — random rarity + type, no typed prompt.
  function randomItem() {
    setRarity(RARITIES[Math.floor(Math.random() * RARITIES.length)]);
    setItemType(TYPES[Math.floor(Math.random() * TYPES.length)]);
    setPrompt("");
    setTimeout(generate, 0);
  }

  return (
    <div className="flex flex-col gap-3">
      <div className="grid grid-cols-2 gap-2">
        <div className="flex flex-col gap-1">
          <label className="text-[var(--color-text-secondary)] text-[10px] font-medium">Rarity</label>
          <select
            className="rounded-lg bg-[var(--color-bg-surface)] border border-[var(--color-border-glass)] px-3 py-1.5 text-[var(--color-text-primary)] focus:outline-none focus:border-[var(--color-gold-bright)] text-xs cursor-pointer"
            value={rarity}
            onChange={(e) => setRarity(e.target.value)}
          >
            {RARITIES.map((r) => <option key={r} value={r}>{r}</option>)}
          </select>
        </div>
        <div className="flex flex-col gap-1">
          <label className="text-[var(--color-text-secondary)] text-[10px] font-medium">Type</label>
          <select
            className="rounded-lg bg-[var(--color-bg-surface)] border border-[var(--color-border-glass)] px-3 py-1.5 text-[var(--color-text-primary)] focus:outline-none focus:border-[var(--color-gold-bright)] text-xs cursor-pointer"
            value={itemType}
            onChange={(e) => setItemType(e.target.value)}
          >
            {TYPES.map((t) => <option key={t} value={t}>{t}</option>)}
          </select>
        </div>
      </div>

      <div className="flex flex-col gap-1">
        <label className="text-[var(--color-text-secondary)] text-[10px] font-medium">
          Additional details (optional)
        </label>
        <input
          className="rounded-lg bg-[var(--color-bg-surface)] border border-[var(--color-border-glass)] px-3 py-2 text-[var(--color-text-primary)] placeholder-[var(--color-text-dim)] focus:outline-none focus:border-[var(--color-gold-bright)] text-sm"
          value={prompt}
          onChange={(e) => setPrompt(e.target.value)}
          placeholder="e.g. a flame dagger that grants fire resistance..."
          onKeyDown={(e) => e.key === "Enter" && generate()}
        />
      </div>

      <button
        onClick={generate}
        disabled={loading}
        className="rounded-lg bg-[var(--color-gold-bright)] text-[var(--color-bg-deep)] px-4 py-2 text-sm font-semibold hover:bg-[var(--color-gold-muted)] transition-colors cursor-pointer disabled:opacity-50"
      >
        {loading ? "⚔ Forging…" : "⚔ Forge Item"}
      </button>
      <button
        onClick={randomItem}
        disabled={loading}
        title="Surprise me — random rarity and type"
        className="rounded-lg bg-[var(--color-bg-surface)] border border-[var(--color-border-glass)] text-[var(--color-text-dim)] px-3 py-2 text-sm hover:text-[var(--color-gold-bright)] hover:border-[var(--color-gold-bright)] transition-colors cursor-pointer disabled:opacity-50"
      >
        🎲 Random
      </button>

      {!item && !loading && !hasParseError && (
        <div className="flex flex-col items-center justify-center py-8 text-center text-[var(--color-text-dim)] text-xs">
          <span>No item yet.</span>
          <span className="mt-1">Pick rarity + type, then Forge.</span>
        </div>
      )}

      {item && (
        <div className="rounded-lg bg-[var(--color-bg-surface)] border border-[var(--color-border-glass)] p-4 flex flex-col gap-3">
          <div className="flex gap-3">
            <div className="shrink-0 w-24">
              <GeneratedImage prompt={artPrompt} nonce={artNonce} aspect="aspect-square" />
              <button
                onClick={() => setArtNonce((n) => n + 1)}
                className="mt-1 w-full text-[10px] text-[var(--color-gold-bright)] hover:text-[var(--color-gold-muted)] cursor-pointer transition-colors"
                title="Regenerate item art"
              >
                ✨ new art
              </button>
            </div>
            <div className="flex-1 min-w-0">
              <div className="flex items-start justify-between">
                <div>
                  <h3 className="font-heading text-lg font-bold" style={{ color: rarityColor[item.rarity] || "var(--color-gold-bright)" }}>
                    {item.name || "Unknown Item"}
                  </h3>
                  <div className="flex gap-2 text-xs text-[var(--color-text-dim)]">
                    <span>{item.rarity || rarity}</span>
                    <span>•</span>
                    <span>{item.type || itemType}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div>
            <span className="text-[var(--color-text-secondary)] text-[10px] font-medium uppercase tracking-wider">Description</span>
            <p className="text-[var(--color-text-primary)] text-sm mt-0.5 leading-relaxed">
              {flattenValue(item.description)}
            </p>
          </div>

          <div className="rounded-lg bg-[var(--color-bg-deep)] border border-[var(--color-border-glass)] p-3">
            <span className="text-[var(--color-gold-bright)] text-[10px] font-medium uppercase tracking-wider">Mechanics</span>
            {structured ? (
              <div className="mt-1 flex flex-col gap-1">
                {/* ponytail: structured fields — attunement/charges/value/weight + one-line effect */}
                <div className="flex flex-wrap gap-x-3 gap-y-0.5 text-xs">
                  <span className="text-[var(--color-text-dim)]">Attunement: </span>
                  <span className="text-[var(--color-text-primary)]">{structured.attunement === "none" || !structured.attunement ? "No" : structured.attunement}</span>
                  <span className="text-[var(--color-text-dim)]">Charges: </span>
                  <span className="text-[var(--color-text-primary)]">{structured.charges || "—"}</span>
                  <span className="text-[var(--color-text-dim)]">Value: </span>
                  <span className="text-[var(--color-text-primary)]">{structured.value || "—"}</span>
                  <span className="text-[var(--color-text-dim)]">Weight: </span>
                  <span className="text-[var(--color-text-primary)]">{structured.weight || "—"}</span>
                </div>
                <p className="text-[var(--color-text-primary)] text-sm mt-1">{structured.effect}</p>
              </div>
            ) : (
              <p className="text-[var(--color-text-primary)] text-sm mt-0.5">{mechanicalText}</p>
            )}
          </div>

          <div>
            <span className="text-[var(--color-text-secondary)] text-[10px] font-medium uppercase tracking-wider">Lore</span>
            <p className="text-[var(--color-text-secondary)] text-sm mt-0.5 italic">
              {flattenValue(item.lore)}
            </p>
          </div>
        </div>
      )}

      {/* Show raw response if JSON parsing failed */}
      {hasParseError && (
        <details className="rounded-lg bg-[var(--color-bg-surface)] border border-[var(--color-border-subtle)]">
          <summary className="px-3 py-2 text-xs text-[var(--color-text-dim)] cursor-pointer hover:text-[var(--color-text-secondary)]">
            Raw LLM response (click to expand)
          </summary>
          <pre className="px-3 pb-3 text-xs text-[var(--color-text-secondary)] overflow-x-auto whitespace-pre-wrap">
            {rawResponse}
          </pre>
        </details>
      )}
    </div>
  );
}