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

interface QuestStep {
  title: string;
  description: string;
  choice?: string;
}

interface QuestResponse {
  title: string;
  hook: string;
  steps: QuestStep[];
  twist: string;
  reward: string;
}

export function QuestDesigner() {
  const [theme, setTheme] = useState("");
  const [level, setLevel] = useState(5);
  const [quest, setQuest] = useState<QuestResponse | null>(null);
  const [currentStep, setCurrentStep] = useState(0);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");

  async function generate() {
    setLoading(true);
    setError("");
    setQuest(null);
    setCurrentStep(0);
    try {
      const result = await invoke<string>("generate", {
        req: {
          prompt: `Design a D&D quest for level ${level} characters.
${theme ? `Theme: ${theme}` : ""}

Provide the response as a JSON object with exactly these keys:
- "title": a catchy quest name
- "hook": 1-2 sentences describing how the party gets involved
- "steps": an array of 3-5 quest steps, each with "title" and "description" (2-3 sentences each), and optionally "choice" (a meaningful decision the party faces)
- "twist": a surprise revelation or complication
- "reward": what the party gains on completion

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 D&D quest 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: 700,
        },
      });
      const parsed = parseLlmJson<QuestResponse>(result);
      if (parsed) {
        setQuest(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">
        <div className="grid grid-cols-3 gap-2">
          <div className="col-span-2 flex flex-col gap-1">
            <label className="text-[var(--color-text-secondary)] text-[10px] font-medium">Quest 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. haunted forest, political intrigue, dragon's lair..."
              onKeyDown={(e) => e.key === "Enter" && generate()}
            />
          </div>
          <div className="flex flex-col gap-1">
            <label className="text-[var(--color-text-secondary)] text-[10px] font-medium">Party Level</label>
            <input
              type="number"
              min={1}
              max={20}
              value={level}
              onChange={(e) => setLevel(parseInt(e.target.value) || 1)}
              className="rounded-lg bg-[var(--color-bg-surface)] border border-[var(--color-border-glass)] px-3 py-2 text-[var(--color-text-primary)] focus:outline-none focus:border-[var(--color-gold-bright)] text-sm font-mono"
            />
          </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 ? "✨ Designing…" : "✨ Design Quest"}
        </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">
          {error}
        </div>
      )}

      {quest && (
        <div className="flex flex-col gap-3">
          {/* Quest title & hook */}
          <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">
              {quest.title}
            </h3>
            <p className="text-[var(--color-text-secondary)] text-sm italic leading-relaxed">
              {quest.hook}
            </p>
          </div>

          {/* Steps - step-through view */}
          {quest.steps?.length > 0 && (
            <div>
              <div className="flex items-center justify-between mb-2">
                <h4 className="text-[var(--color-text-secondary)] text-xs font-medium">
                  Quest Steps
                </h4>
                <div className="flex gap-1">
                  {quest.steps.map((_, i) => (
                    <button
                      key={i}
                      onClick={() => setCurrentStep(i)}
                      className={`w-6 h-6 rounded-full text-[10px] font-mono flex items-center justify-center cursor-pointer transition-colors ${
                        i === currentStep
                          ? "bg-[var(--color-gold-bright)] text-[var(--color-bg-deep)]"
                          : i < currentStep
                            ? "bg-[var(--color-success)]/20 text-[var(--color-success)]"
                            : "bg-[var(--color-bg-surface)] text-[var(--color-text-dim)] border border-[var(--color-border-subtle)]"
                      }`}
                    >
                      {i + 1}
                    </button>
                  ))}
                </div>
              </div>

              <div className="rounded-lg bg-[var(--color-bg-surface)] border border-[var(--color-border-glass)] p-4">
                <h5 className="text-[var(--color-text-primary)] text-sm font-semibold mb-1">
                  Step {currentStep + 1}: {quest.steps[currentStep].title}
                </h5>
                <p className="text-[var(--color-text-secondary)] text-sm leading-relaxed">
                  {quest.steps[currentStep].description}
                </p>
                {quest.steps[currentStep].choice && (
                  <div className="mt-2 rounded-lg bg-[var(--color-bg-deep)] border-l-2 border-[var(--color-gold-bright)] px-3 py-2">
                    <span className="text-[var(--color-gold-bright)] text-[10px] font-medium uppercase tracking-wider">Choice</span>
                    <p className="text-[var(--color-text-primary)] text-sm mt-0.5">{quest.steps[currentStep].choice}</p>
                  </div>
                )}
                <div className="flex justify-between mt-3">
                  <button
                    onClick={() => setCurrentStep(Math.max(0, currentStep - 1))}
                    disabled={currentStep === 0}
                    className="text-[var(--color-text-dim)] hover:text-[var(--color-text-primary)] text-xs cursor-pointer disabled:opacity-30 disabled:cursor-default"
                  >
                    ← Previous
                  </button>
                  <button
                    onClick={() => setCurrentStep(Math.min(quest.steps.length - 1, currentStep + 1))}
                    disabled={currentStep === quest.steps.length - 1}
                    className="text-[var(--color-gold-bright)] hover:text-[var(--color-gold-muted)] text-xs cursor-pointer disabled:opacity-30 disabled:cursor-default"
                  >
                    Next →
                  </button>
                </div>
              </div>
            </div>
          )}

          {/* Twist */}
          {quest.twist && (
            <div className="rounded-lg border-l-2 border-[var(--color-danger)] bg-[var(--color-bg-surface)] px-4 py-3">
              <span className="text-[var(--color-danger)] text-[10px] font-medium uppercase tracking-wider">Twist</span>
              <p className="text-[var(--color-text-primary)] text-sm mt-0.5">{quest.twist}</p>
            </div>
          )}

          {/* Reward */}
          {quest.reward && (
            <div className="rounded-lg border-l-2 border-[var(--color-gold-bright)] bg-[var(--color-bg-surface)] px-4 py-3">
              <span className="text-[var(--color-gold-bright)] text-[10px] font-medium uppercase tracking-wider">Reward</span>
              <p className="text-[var(--color-text-primary)] text-sm mt-0.5">{quest.reward}</p>
            </div>
          )}
        </div>
      )}
    </div>
  );
}