"use client";

import { useEffect, useState } from "react";
import { fetchAllSignals, Signal, formatRelativeTime, getSeverityColor } from "../lib/api";

export default function ThoughtStreams() {
  const [signals, setSignals] = useState<Signal[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function load() {
      try {
        const all = await fetchAllSignals();
        const flat = all
          .flatMap((g) => g.signals)
          .sort(
            (a, b) =>
              new Date(b.metadata.timestamp).getTime() -
              new Date(a.metadata.timestamp).getTime()
          )
          .slice(0, 10);
        setSignals(flat);
      } catch {
        // ignore
      } finally {
        setLoading(false);
      }
    }
    load();
  }, []);

  return (
    <div className="glass-card p-6 rounded-2xl flex flex-col">
      <h3 className="text-sm font-bold tracking-tight text-white uppercase mb-6">
        Thought Streams
      </h3>

      <div
        className="space-y-4 flex-1 overflow-y-auto pr-2 custom-scrollbar"
        style={{ maxHeight: "16rem" }}
      >
        {loading && (
          <div className="flex items-center gap-2 text-zinc-600 text-[10px] font-mono-data">
            <span className="material-symbols-outlined animate-spin text-sm">autorenew</span>
            Loading streams...
          </div>
        )}

        {!loading && signals.length === 0 && (
          <p className="text-[10px] text-zinc-600 font-mono-data">
            No signals yet. Streams will appear here as groups send messages.
          </p>
        )}

        {signals.map((sig, i) => (
          <div key={i} className="flex items-start space-x-3 text-[10px]">
            <span className="font-mono-data shrink-0" style={{ color: "#A78BFA" }}>
              {formatRelativeTime(sig.metadata.timestamp)}
            </span>
            <p
              className="font-mono-data leading-relaxed"
              style={{ color: "rgba(249,245,248,0.6)" }}
            >
              <span style={{ color: getSeverityColor(sig.metadata.severity) }}>
                {sig.metadata.type.toUpperCase()}:
              </span>{" "}
              {sig.document.slice(0, 80)}
              {sig.document.length > 80 ? "…" : ""}
            </p>
          </div>
        ))}
      </div>

      <button
        className="mt-6 w-full py-3 rounded-xl text-[10px] font-mono-data uppercase tracking-widest transition-all hover:opacity-80"
        style={{
          backgroundColor: "rgba(167,139,250,0.05)",
          border: "1px solid rgba(167,139,250,0.2)",
          color: "#A78BFA",
        }}
      >
        Export Intelligence Data
      </button>
    </div>
  );
}
