"use client";

import { useEffect, useState } from "react";

type Msg = { id: string; sender: string; content: string; created_at: string };

export function LiveAgentChat({ whatsapp }: { whatsapp: string }) {
  const [messages, setMessages] = useState<Msg[]>([]);
  const [input, setInput] = useState("");
  const [until, setUntil] = useState<string | null>(null);
  const [error, setError] = useState("");

  async function load() {
    const res = await fetch("/api/agent/messages");
    const json = await res.json();
    if (!res.ok) {
      setError(json.error || "Could not load thread");
      return;
    }
    setMessages(json.messages || []);
    setUntil(json.until);
  }

  useEffect(() => {
    load();
    const t = setInterval(load, 12000);
    return () => clearInterval(t);
  }, []);

  async function send(e: React.FormEvent) {
    e.preventDefault();
    const content = input.trim();
    if (!content) return;
    setInput("");
    const res = await fetch("/api/agent/messages", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ content }),
    });
    const json = await res.json();
    if (!res.ok) {
      setError(json.error || "Send failed");
      return;
    }
    setMessages(json.messages || []);
  }

  const wa = whatsapp.replace(/[^\d]/g, "");

  return (
    <div className="rounded-3xl border border-forest/10 bg-cream">
      <div className="flex items-center justify-between border-b border-forest/10 px-5 py-4">
        <div>
          <p className="font-display text-xl text-forest">Live coach</p>
          {until ? (
            <p className="text-xs text-forest/60">Pass until {new Date(until).toLocaleDateString()}</p>
          ) : null}
        </div>
        {wa ? (
          <a
            className="rounded-full bg-[#128C7E] px-4 py-2 text-xs font-semibold text-white"
            href={`https://wa.me/${wa}?text=${encodeURIComponent("Hi, I have a CediForge live coach pass.")}`}
            target="_blank"
            rel="noreferrer"
          >
            WhatsApp
          </a>
        ) : null}
      </div>
      <div className="max-h-[28rem] space-y-3 overflow-y-auto p-5 text-sm">
        {messages.length === 0 ? (
          <p className="text-forest/60">No messages yet. Ask about a stuck supplier, ad, or client.</p>
        ) : (
          messages.map((m) => (
            <div
              key={m.id}
              className={`max-w-[85%] rounded-2xl px-3 py-2 ${
                m.sender === "user" ? "ml-auto bg-forest text-cream" : "bg-paper text-forest"
              }`}
            >
              {m.content}
            </div>
          ))
        )}
      </div>
      {error ? <p className="px-5 text-xs text-terra">{error}</p> : null}
      <form onSubmit={send} className="flex gap-2 border-t border-forest/10 p-4">
        <input
          value={input}
          onChange={(e) => setInput(e.target.value)}
          placeholder="Message a human coach…"
          className="flex-1 rounded-full border border-forest/10 bg-white px-4 py-2 text-sm"
        />
        <button className="rounded-full bg-terra px-4 py-2 text-sm font-semibold text-cream">Send</button>
      </form>
    </div>
  );
}
