"use client";

import { useRef, useState } from "react";

type Msg = { role: "user" | "assistant"; content: string };

export function TutorPanel({
  course,
  level,
  prompts,
}: {
  course: string;
  level: string;
  prompts: string[];
}) {
  const [open, setOpen] = useState(true);
  const [input, setInput] = useState("");
  const [busy, setBusy] = useState(false);
  const [messages, setMessages] = useState<Msg[]>([
    {
      role: "assistant",
      content:
        "I am your lesson tutor. Ask for a Ghana-specific script, a number in cedis, a role-play, or a quiz on this level.",
    },
  ]);
  const scroller = useRef<HTMLDivElement>(null);

  async function send(text: string) {
    const content = text.trim();
    if (!content || busy) return;
    const next = [...messages, { role: "user" as const, content }];
    setMessages(next);
    setInput("");
    setBusy(true);
    const res = await fetch("/api/chat", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ course, level, messages: next }),
    });
    if (!res.ok || !res.body) {
      setMessages([
        ...next,
        { role: "assistant", content: "The tutor could not reply just now. Try again in a moment." },
      ]);
      setBusy(false);
      return;
    }
    const reader = res.body.getReader();
    const decoder = new TextDecoder();
    let assistant = "";
    setMessages([...next, { role: "assistant", content: "" }]);
    while (true) {
      const { value, done } = await reader.read();
      if (done) break;
      assistant += decoder.decode(value, { stream: true });
      setMessages([...next, { role: "assistant", content: assistant }]);
      scroller.current?.scrollTo({ top: scroller.current.scrollHeight });
    }
    setBusy(false);
  }

  return (
    <aside className="flex h-full min-h-[28rem] flex-col overflow-hidden rounded-3xl border border-forest/15 bg-forest text-cream">
      <div className="flex items-center justify-between px-4 py-3">
        <div>
          <p className="text-[10px] uppercase tracking-[0.25em] text-gold-2">In this lesson</p>
          <p className="font-display text-lg">Tutor</p>
        </div>
        <button type="button" className="text-xs text-cream/70 md:hidden" onClick={() => setOpen((v) => !v)}>
          {open ? "Hide" : "Show"}
        </button>
      </div>
      {open ? (
        <>
          <div ref={scroller} className="flex-1 space-y-3 overflow-y-auto px-4 pb-3 text-sm">
            {messages.map((m, i) => (
              <div
                key={i}
                className={`rounded-2xl px-3 py-2 leading-relaxed ${
                  m.role === "user" ? "ml-6 bg-white/10" : "mr-2 bg-paper/10"
                }`}
              >
                {m.content}
              </div>
            ))}
          </div>
          <div className="flex flex-wrap gap-2 px-4 pb-2">
            {prompts.slice(0, 3).map((p) => (
              <button
                key={p}
                type="button"
                onClick={() => send(p)}
                className="rounded-full border border-gold/30 px-2.5 py-1 text-[11px] text-gold-2"
              >
                {p}
              </button>
            ))}
          </div>
          <form
            className="flex gap-2 border-t border-white/10 p-3"
            onSubmit={(e) => {
              e.preventDefault();
              send(input);
            }}
          >
            <input
              value={input}
              onChange={(e) => setInput(e.target.value)}
              placeholder="Ask the tutor…"
              className="flex-1 rounded-full bg-white/10 px-4 py-2 text-sm text-cream outline-none placeholder:text-cream/40"
            />
            <button
              disabled={busy}
              className="rounded-full bg-gold px-4 py-2 text-sm font-semibold text-forest disabled:opacity-50"
            >
              Send
            </button>
          </form>
        </>
      ) : null}
    </aside>
  );
}
