import { parseLlmJson, ensureArray, flattenValue } from "../lib/llm-parse";
import { useState } from "react";
import { invoke } from "@tauri-apps/api/core";
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";
import { RACES, BACKGROUNDS, ALIGNMENTS, randomName } from "../lib/npc-data";
import { Dice5 } from "lucide-react";

interface NpcResponse {
  bio: string;
  personality: string[];
  goals: string[];
}

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

export function NpcGenerator({ prefill, onPrefillConsumed }: Props = {}) {
  const [race, setRace] = useState("Dwarf");
  const [background, setBackground] = useState("Guild Artisan");
  const [alignment, setAlignment] = useState("Chaotic Good");
  const [name, setName] = useState("");
  const [npc, setNpc] = useState<NpcResponse | null>(null);
  const [loading, setLoading] = useState(false);
  const [portraitNonce, setPortraitNonce] = useState(0);
  // ponytail: in-place edit of personality/goals — add/remove without regenerating.
  const [newTrait, setNewTrait] = useState("");
  const [newGoal, setNewGoal] = useState("");
  const { addToast } = useToast();

  usePrefillEffect(prefill ?? null, "npc", () => onPrefillConsumed?.(), (g) => {
    const parsed = parseLlmJson<NpcResponse>(g.data);
    if (parsed) {
      setNpc(parsed);
      if (g.title) setName(g.title);
      addToast(`Loaded "${g.title}" from history`, "info");
    }
  });

  // ponytail: portrait prompt mirrors the NPC inputs; FLUX.2 renders readable
  // text so we drop the name in-image when one is given.
  const portraitPrompt = npc ? `fantasy oil-painting portrait of a ${race} ${background.toLowerCase()}, ${alignment.toLowerCase()} demeanor, ${ensureArray(npc.personality).slice(0, 2).map(flattenValue).join(", ")}, dramatic lighting, 1024x1024${name ? `, name "${name}" rendered as a caption` : ""}` : null;

  function removeTrait(i: number) {
    if (!npc) return;
    setNpc({ ...npc, personality: npc.personality.filter((_, j) => j !== i) });
  }
  function addTrait() {
    if (!npc || !newTrait.trim()) return;
    setNpc({ ...npc, personality: [...npc.personality, newTrait.trim()] });
    setNewTrait("");
  }
  function removeGoal(i: number) {
    if (!npc) return;
    setNpc({ ...npc, goals: npc.goals.filter((_, j) => j !== i) });
  }
  function addGoal() {
    if (!npc || !newGoal.trim()) return;
    setNpc({ ...npc, goals: [...npc.goals, newGoal.trim()] });
    setNewGoal("");
  }

  async function generate() {
    setLoading(true);
    setNpc(null);
    try {
      const prompt = `Create a detailed NPC for a fantasy RPG:
${name ? `Name: ${name}` : "Name: (generate one)"}
Race: ${race}
Background: ${background}
Alignment: ${alignment}

Provide the response as a JSON object with exactly these keys:
- "bio": a 2-3 sentence backstory
- "personality": an array of 3-5 personality traits (each trait must be a string, not an object)
- "goals": an array of 2-3 goals or motivations (each goal must be a string, not an object)

IMPORTANT: Return ONLY a raw JSON object. NO markdown fences, NO code blocks, NO extra text. Start with { and end with }.`;

      const result = await invoke<string>("generate", {
        req: { prompt, system: "You are a creative D&D dungeon master. You MUST respond with ONLY valid JSON. No markdown fences, no code blocks, no explanation. Just the JSON object.", temperature: 0.8, max_tokens: 512, ragQuery: `${race} ${background} ${alignment} NPC` },
      });

      // Try to parse JSON from the response
      const parsed = parseLlmJson<NpcResponse>(result);
      if (parsed) {
        setNpc(parsed);
        addToast("NPC generated", "success");
        // ponytail: persist to history so the user can re-open it later.
        const title = name.trim() || extractTitle("npc", result, `${race} ${background}`);
        const source = `${race} ${background} (${alignment})${name ? `, "${name}"` : ""}`;
        void addGeneration({ kind: "npc", title, data: result, source });
        // ponytail: ingest every generated NPC into lore so later generations
        // stay consistent with the growing cast.
        const persona = ensureArray(parsed.personality).map(flattenValue).join(", ");
        const goals = ensureArray(parsed.goals).map(flattenValue).join("; ");
        void addToLore(
          `NPC: ${name || race + " " + background}`,
          `${name || "An unnamed NPC"} — a ${race} ${background} (${alignment}). ${parsed.bio}\nPersonality: ${persona}\nGoals: ${goals}`,
        );
      } else {
        addToast("LLM returned an unparseable response", "error");
      }
    } catch (e) {
      addToast(`NPC generation failed: ${e}`, "error");
    }
    setLoading(false);
  }

  return (
    <div className="flex flex-col gap-3 h-full overflow-y-auto">
      {/* Controls */}
      <div className="grid grid-cols-2 gap-2">
        <div className="flex flex-col gap-1">
          <label className="text-[var(--color-text-secondary)] text-xs font-medium">Name</label>
          <div className="flex gap-1.5">
            <input
              className="flex-1 min-w-0 rounded-lg bg-[var(--color-bg-surface)] border border-[var(--color-border-glass)] px-3 py-1.5 text-[var(--color-text-primary)] placeholder-[var(--color-text-dim)] focus:outline-none focus:border-[var(--color-gold-bright)] text-sm"
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder="Random"
            />
            <button
              type="button"
              onClick={() => setName(randomName(race))}
              className="rounded-lg bg-[var(--color-bg-surface)] border border-[var(--color-border-glass)] px-2 text-[var(--color-text-dim)] hover:text-[var(--color-gold-bright)] hover:border-[var(--color-gold-bright)] transition-colors cursor-pointer"
              title={`Random ${race} name`}
              aria-label={`Random ${race} name`}
            >
              <Dice5 size={14} />
            </button>
          </div>
        </div>
        <div className="flex flex-col gap-1">
          <label className="text-[var(--color-text-secondary)] text-xs font-medium">Race</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-sm cursor-pointer"
            value={race}
            onChange={(e) => setRace(e.target.value)}
          >
            {RACES.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-xs font-medium">Background</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-sm cursor-pointer"
            value={background}
            onChange={(e) => setBackground(e.target.value)}
          >
            {BACKGROUNDS.map((b) => <option key={b} value={b}>{b}</option>)}
          </select>
        </div>
        <div className="flex flex-col gap-1">
          <label className="text-[var(--color-text-secondary)] text-xs font-medium">Alignment</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-sm cursor-pointer"
            value={alignment}
            onChange={(e) => setAlignment(e.target.value)}
          >
            {ALIGNMENTS.map((a) => <option key={a} value={a}>{a}</option>)}
          </select>
        </div>
      </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 ? "✨ Generating…" : "✨ Generate NPC"}
      </button>

      {/* Result */}

      {npc && (
        <div className="rounded-lg bg-[var(--color-bg-surface)] border border-[var(--color-border-glass)] p-3 flex flex-col gap-2">
          <div className="flex gap-3">
            <div className="shrink-0 w-24">
              <GeneratedImage prompt={portraitPrompt} nonce={portraitNonce} aspect="aspect-square" />
              <button
                onClick={() => setPortraitNonce((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 portrait"
              >
                ✨ new portrait
              </button>
            </div>
            <div className="flex-1 min-w-0">
              <h3 className="font-heading text-[var(--color-gold-bright)] text-sm">
                {name || "NPC"}
              </h3>
              <p className="text-[var(--color-text-primary)] text-sm leading-relaxed">{npc.bio}</p>
            </div>
          </div>
          <div>
            <span className="text-[var(--color-text-secondary)] text-xs font-medium">Personality:</span>
            <div className="flex flex-wrap gap-1 mt-1">
              {npc.personality.map((p, i) => (
                <span
                  key={i}
                  onClick={() => removeTrait(i)}
                  className="rounded-full bg-[var(--color-gold-glow)] text-[var(--color-gold-bright)] px-2 py-0.5 text-xs cursor-pointer hover:opacity-70"
                  title="Remove"
                >
                  {p} ×
                </span>
              ))}
              <input
                className="rounded-full bg-[var(--color-bg-deep)] border border-[var(--color-border-subtle)] px-2 py-0.5 text-xs text-[var(--color-text-primary)] focus:outline-none focus:border-[var(--color-gold-bright)] w-24"
                value={newTrait}
                onChange={(e) => setNewTrait(e.target.value)}
                onKeyDown={(e) => e.key === "Enter" && addTrait()}
                placeholder="+ trait"
                aria-label="Add personality trait"
              />
            </div>
          </div>
          <div>
            <span className="text-[var(--color-text-secondary)] text-xs font-medium">Goals:</span>
            <ul className="text-[var(--color-text-primary)] text-xs mt-1 space-y-0.5">
              {npc.goals.map((g, i) => (
                <li key={i} className="flex items-center gap-1.5">
                  <span className="text-[var(--color-gold-bright)]">•</span>
                  <span className="flex-1">{g}</span>
                  <button onClick={() => removeGoal(i)} className="text-[var(--color-text-dim)] hover:text-[var(--color-danger)] cursor-pointer text-[10px]" title="Remove goal">×</button>
                </li>
              ))}
            </ul>
            <input
              className="mt-1 rounded bg-[var(--color-bg-deep)] border border-[var(--color-border-subtle)] px-2 py-0.5 text-xs text-[var(--color-text-primary)] focus:outline-none focus:border-[var(--color-gold-bright)] w-full"
              value={newGoal}
              onChange={(e) => setNewGoal(e.target.value)}
              onKeyDown={(e) => e.key === "Enter" && addGoal()}
              placeholder="+ add a goal…"
              aria-label="Add goal"
            />
          </div>
        </div>
      )}
    </div>
  );
}