"use client";

import { useState } from "react";

type Thread = { user_id: string; name: string; email: string; last_at: string; n: number };
type Msg = { id: string; sender: string; content: string; created_at: string };

export default function StaffPage() {
  const [pin, setPin] = useState("");
  const [threads, setThreads] = useState<Thread[]>([]);
  const [active, setActive] = useState<string | null>(null);
  const [messages, setMessages] = useState<Msg[]>([]);
  const [reply, setReply] = useState("");
  const [error, setError] = useState("");

  async function load(userId?: string) {
    const res = await fetch(`/api/staff${userId ? `?user=${userId}` : ""}`, {
      headers: { "x-staff-pin": pin },
    });
    const json = await res.json();
    if (!res.ok) {
      setError(json.error || "Denied");
      return;
    }
    setError("");
    setThreads(json.threads || []);
    if (userId) setMessages(json.messages || []);
  }

  async function send(e: React.FormEvent) {
    e.preventDefault();
    if (!active) return;
    await fetch("/api/staff", {
      method: "POST",
      headers: { "Content-Type": "application/json", "x-staff-pin": pin },
      body: JSON.stringify({ userId: active, content: reply }),
    });
    setReply("");
    load(active);
  }

  return (
    <div className="mx-auto max-w-5xl px-4 py-12">
      <h1 className="font-display text-3xl text-forest">Coach desk</h1>
      <p className="mt-2 text-sm text-forest/70">Staff pin required. Default local pin is 2468 unless STAFF_PIN is set.</p>
      <div className="mt-4 flex gap-2">
        <input
          type="password"
          value={pin}
          onChange={(e) => setPin(e.target.value)}
          placeholder="Staff pin"
          className="rounded-xl border border-forest/15 bg-white px-3 py-2 text-sm"
        />
        <button onClick={() => load()} className="rounded-full bg-forest px-4 py-2 text-sm text-gold-2">
          Open desk
        </button>
      </div>
      {error ? <p className="mt-2 text-sm text-terra">{error}</p> : null}
      <div className="mt-8 grid gap-6 md:grid-cols-[240px_minmax(0,1fr)]">
        <ul className="space-y-2">
          {threads.map((t) => (
            <li key={t.user_id}>
              <button
                type="button"
                onClick={() => {
                  setActive(t.user_id);
                  load(t.user_id);
                }}
                className={`w-full rounded-2xl px-3 py-2 text-left text-sm ${
                  active === t.user_id ? "bg-forest text-cream" : "bg-cream"
                }`}
              >
                <span className="block font-medium">{t.name}</span>
                <span className="block text-xs opacity-70">{t.n} messages</span>
              </button>
            </li>
          ))}
        </ul>
        <div className="rounded-3xl bg-cream p-4">
          <div className="min-h-64 space-y-2">
            {messages.map((m) => (
              <p key={m.id} className="text-sm">
                <strong>{m.sender}:</strong> {m.content}
              </p>
            ))}
          </div>
          {active ? (
            <form onSubmit={send} className="mt-4 flex gap-2">
              <input
                value={reply}
                onChange={(e) => setReply(e.target.value)}
                className="flex-1 rounded-full border border-forest/10 px-4 py-2 text-sm"
              />
              <button className="rounded-full bg-terra px-4 py-2 text-sm text-cream">Reply</button>
            </form>
          ) : (
            <p className="text-sm text-forest/50">Select a learner.</p>
          )}
        </div>
      </div>
    </div>
  );
}
