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

interface WorldResponse {
  name: string;
  description: string;
  regions: string[];
  landmarks: string[];
  conflicts: string[];
  cultures: string[];
}

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

export function WorldBuilder({ prefill, onPrefillConsumed }: Props = {}) {
  // ponytail: persist theme + last world so a reload keeps the DM's work.
  const [theme, setTheme] = usePersistentState<string>("world.theme", "high fantasy");
  const [world, setWorld] = usePersistentState<WorldResponse | null>("world.last", null);
  const [loading, setLoading] = useState(false);
  const { addToast } = useToast();

  // ponytail: genre presets as a quick-pick row.
  const THEME_PRESETS = [
    "high fantasy", "dark fantasy", "sword & sorcery",
    "steampunk", "post-apocalyptic", "horror", "sci-fantasy",
  ];

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

  async function generate() {
    setLoading(true);
    setWorld(null);
    try {
      const result = await invoke<string>("generate", {
        req: {
          prompt: `Create a detailed fantasy world with the theme: "${theme}".

Provide the response as a JSON object with exactly these keys:
- "name": the world's name
- "description": a 2-3 sentence overview
- "regions": an array of 3-4 region names with brief descriptions (each must be a string)
- "landmarks": an array of 2-3 notable landmarks (each must be a string)
- "conflicts": an array of 2-3 major conflicts or tensions (each must be a string)
- "cultures": an array of 2-3 distinct cultures or peoples (each must be a string)

IMPORTANT: Return ONLY a raw JSON object. NO markdown fences, NO code blocks, NO extra text. Start with { and end with }.`,
          system: "You are a creative world-building DM. You MUST respond with ONLY valid JSON. No markdown fences, no code blocks, no explanation. Just the JSON object.",
          temperature: 0.9,
          max_tokens: 600,
          ragQuery: `fantasy world ${theme} regions landmarks cultures`,
        },
      });
      const parsed = parseLlmJson<WorldResponse>(result);
      if (parsed) {
        setWorld(parsed);
        addToast("World generated", "success");
        const title = extractTitle("world", result, theme);
        const source = `Theme: ${theme}`;
        void addGeneration({ kind: "world", title, data: result, source });
        const regions = ensureArray(parsed.regions).map(flattenValue).join("; ");
        const landmarks = ensureArray(parsed.landmarks).map(flattenValue).join("; ");
        const conflicts = ensureArray(parsed.conflicts).map(flattenValue).join("; ");
        const cultures = ensureArray(parsed.cultures).map(flattenValue).join("; ");
        void addToLore(
          `World: ${parsed.name || theme}`,
          `${parsed.name || "World"} (${theme}). ${parsed.description}\nRegions: ${regions}\nLandmarks: ${landmarks}\nConflicts: ${conflicts}\nCultures: ${cultures}`,
        );
      } else {
        addToast("LLM returned an unparseable response", "error");
      }
    } catch (e) {
      addToast(`World generation failed: ${e}`, "error");
    }
    setLoading(false);
  }

  return (
    <div className="flex flex-col gap-4">
      <div className="flex flex-col gap-2">
        <label className="text-[var(--color-text-secondary)] text-xs font-medium">
          World Theme
        </label>
        <div className="flex flex-wrap gap-1.5 mb-1">
          {THEME_PRESETS.map((t) => (
            <button
              key={t}
              type="button"
              onClick={() => setTheme(t)}
              className={`rounded-lg px-2.5 py-1 text-xs border transition-colors cursor-pointer ${
                theme === t
                  ? "bg-[var(--color-gold-glow)] border-[var(--color-gold-bright)] text-[var(--color-gold-bright)]"
                  : "bg-[var(--color-bg-surface)] border-[var(--color-border-glass)] text-[var(--color-text-dim)] hover:text-[var(--color-text-secondary)]"
              }`}
            >
              {t}
            </button>
          ))}
        </div>
        <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={theme}
          onChange={(e) => setTheme(e.target.value)}
          placeholder="e.g. high fantasy, dark post-apocalyptic, steampunk..."
          onKeyDown={(e) => e.key === "Enter" && generate()}
        />
        <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 World"}
        </button>
      </div>


      {world && (
        <div className="flex flex-col gap-3">
          {/* World name and description */}
          <div className="rounded-lg bg-[var(--color-bg-surface)] border border-[var(--color-border-glass)] p-4">
            <h3 className="font-heading text-[var(--color-gold-bright)] text-lg font-bold mb-1">
              {world.name}
            </h3>
            <p className="text-[var(--color-text-primary)] text-sm leading-relaxed">
              {world.description}
            </p>
          </div>

          {/* Regions */}
          {world.regions?.length > 0 && (
            <div>
              <h4 className="text-[var(--color-text-secondary)] text-xs font-medium mb-1.5">
                🏔 Regions
              </h4>
              <div className="flex flex-col gap-1.5">
                {ensureArray(world.regions).map((r, i) => (
                  <div key={i} className="rounded-lg bg-[var(--color-bg-surface)] border border-[var(--color-border-subtle)] px-3 py-2 text-sm text-[var(--color-text-primary)]">
                    {flattenValue(r)}
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Landmarks */}
          {world.landmarks?.length > 0 && (
            <div>
              <h4 className="text-[var(--color-text-secondary)] text-xs font-medium mb-1.5">
                🏛 Landmarks
              </h4>
              <div className="flex flex-wrap gap-1.5">
                {ensureArray(world.landmarks).map((l, i) => (
                  <span key={i} className="rounded-full bg-[var(--color-gold-glow)] text-[var(--color-gold-bright)] px-3 py-1 text-xs">
                    {flattenValue(l)}
                  </span>
                ))}
              </div>
            </div>
          )}

          {/* Conflicts */}
          {world.conflicts?.length > 0 && (
            <div>
              <h4 className="text-[var(--color-text-secondary)] text-xs font-medium mb-1.5">
                ⚔ Conflicts
              </h4>
              <div className="flex flex-col gap-1.5">
                {ensureArray(world.conflicts).map((c, i) => (
                  <div key={i} className="rounded-lg bg-[var(--color-bg-surface)] border-l-2 border-[var(--color-danger)] px-3 py-2 text-sm text-[var(--color-text-primary)]">
                    {flattenValue(c)}
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Cultures */}
          {world.cultures?.length > 0 && (
            <div>
              <h4 className="text-[var(--color-text-secondary)] text-xs font-medium mb-1.5">
                👥 Cultures
              </h4>
              <div className="flex flex-wrap gap-1.5">
                {ensureArray(world.cultures).map((c, i) => (
                  <span key={i} className="rounded-full bg-[var(--color-bg-surface)] border border-[var(--color-info)]/30 text-[var(--color-info)] px-3 py-1 text-xs">
                    {flattenValue(c)}
                  </span>
                ))}
              </div>
            </div>
          )}
        </div>
      )}
    </div>
  );
}