import { useState } from "react";
import { invoke } from "@tauri-apps/api/core";

export function SessionLogger() {
  const [notes, setNotes] = useState("");
  const [summary, setSummary] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [entries, setEntries] = useState<{ text: string; time: string }[]>([]);

  function addEntry() {
    if (!notes.trim()) return;
    setEntries((prev) => [
      { text: notes.trim(), time: new Date().toLocaleTimeString() },
      ...prev,
    ]);
    setNotes("");
  }

  async function summarize() {
    if (entries.length === 0) return;
    setLoading(true);
    setError("");
    try {
      const sessionText = entries
        .map((e) => `[${e.time}] ${e.text}`)
        .join("\n");
      const result = await invoke<string>("generate", {
        req: {
          prompt: `Summarize the following D&D session notes and suggest 2-3 hooks for the next session:\n\n${sessionText}`,
          system: "You are a helpful D&D session summarizer. Be concise and creative.",
          temperature: 0.7,
          max_tokens: 512,
        },
      });
      setSummary(result);
    } catch (e) {
      setError(String(e));
    }
    setLoading(false);
  }

  return (
    <div className="flex gap-3 h-full">
      {/* Notes column */}
      <div className="flex flex-col gap-2 flex-1">
        <textarea
          className="flex-1 rounded-lg bg-[var(--color-bg-surface)] border border-[var(--color-border-glass)] p-3 text-[var(--color-text-primary)] placeholder-[var(--color-text-dim)] focus:outline-none focus:border-[var(--color-gold-bright)] text-sm resize-none"
          value={notes}
          onChange={(e) => setNotes(e.target.value)}
          onKeyDown={(e) => {
            if (e.key === "Enter" && !e.shiftKey) {
              e.preventDefault();
              addEntry();
            }
          }}
          placeholder="Type a session note, press Enter to add…"
        />
        <div className="flex gap-2">
          <button
            onClick={addEntry}
            className="rounded-lg bg-[var(--color-bg-surface)] border border-[var(--color-border-glass)] text-[var(--color-text-secondary)] px-3 py-1.5 text-xs hover:border-[var(--color-gold-bright)] hover:text-[var(--color-gold-bright)] transition-colors cursor-pointer"
          >
            Add Note
          </button>
          <button
            onClick={summarize}
            disabled={loading || entries.length === 0}
            className="rounded-lg bg-[var(--color-gold-bright)] text-[var(--color-bg-deep)] px-3 py-1.5 text-xs font-semibold hover:bg-[var(--color-gold-muted)] transition-colors cursor-pointer disabled:opacity-50"
          >
            {loading ? "Summarizing…" : "✨ AI Summary"}
          </button>
        </div>
        <div className="flex-1 overflow-y-auto">
          {entries.map((e, i) => (
            <div key={i} className="flex gap-2 py-1 border-b border-[var(--color-border-subtle)]">
              <span className="text-[var(--color-text-dim)] text-xs font-mono shrink-0">
                {e.time}
              </span>
              <span className="text-[var(--color-text-primary)] text-xs">{e.text}</span>
            </div>
          ))}
        </div>
      </div>

      {/* AI Summary column */}
      <div className="flex-1 flex flex-col">
        <h3 className="text-xs font-medium text-[var(--color-text-secondary)] mb-2">AI Summary</h3>
        {error && (
          <div className="rounded-lg bg-[var(--color-danger)]/10 border border-[var(--color-danger)]/30 p-2 text-[var(--color-danger)] text-xs mb-2">
            {error}
          </div>
        )}
        <div className="flex-1 rounded-lg bg-[var(--color-bg-surface)] border border-[var(--color-border-glass)] p-3 text-[var(--color-text-primary)] text-sm overflow-y-auto">
          {summary || (
            <span className="text-[var(--color-text-dim)] italic">
              Add session notes and click "AI Summary" to generate a recap and next-session hooks.
            </span>
          )}
        </div>
      </div>
    </div>
  );
}