import { parseLlmJson, ensureArray, flattenValue } from "../lib/llm-parse";
import { useState } from "react";
import { invoke } from "@tauri-apps/api/core";

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

export function WorldBuilder() {
  const [theme, setTheme] = useState("high fantasy");
  const [world, setWorld] = useState<WorldResponse | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");

  async function generate() {
    setLoading(true);
    setError("");
    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,
        },
      });
      const parsed = parseLlmJson<WorldResponse>(result);
      if (parsed) {
        setWorld(parsed);
      } else {
        setError("Could not parse LLM response. Try again or check your LLM connection.");
      }
    } catch (e) {
      setError(String(e));
    }
    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>
        <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>

      {error && (
        <div className="rounded-lg bg-[var(--color-danger)]/10 border border-[var(--color-danger)]/30 p-3 text-[var(--color-danger)] text-xs overflow-x-auto">
          {error}
        </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>
  );
}