"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { ArrowUpRight, Sunrise } from "lucide-react";
import Panel from "./Panel";

interface BriefStat { label: string; value: string }
interface Brief {
  ok: boolean;
  dateLabel: string;
  greeting: string;
  headline: string;
  spoken: string;
  focus: string[];
  stats: BriefStat[];
  generatedAt: number;
}

type LoadState = "loading" | "ready" | "empty" | "generating" | "error";

const MAX_FOCUS_SHOWN = 3;

// DailyBriefCard — the latest saved Hermes/Apollo briefing. Reads history only
// (cheap); generating a fresh brief is a deliberate button press because it
// walks the vault and calls a model.
export default function DailyBriefCard() {
  const [state, setState] = useState<LoadState>("loading");
  const [brief, setBrief] = useState<Brief | null>(null);

  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const r = await fetch("/api/hermes/briefing?history=1&limit=1", { cache: "no-store" });
        const j = await r.json();
        if (cancelled) return;
        const latest: Brief | undefined = j?.briefings?.[0];
        if (latest?.headline) { setBrief(latest); setState("ready"); }
        else setState("empty");
      } catch {
        if (!cancelled) setState("empty"); // a dead endpoint reads as "no brief yet"
      }
    })();
    return () => { cancelled = true; };
  }, []);

  const generate = async () => {
    setState("generating");
    try {
      const r = await fetch("/api/hermes/briefing?range=daily", { cache: "no-store" });
      const j: Brief = await r.json();
      if (j?.headline) { setBrief(j); setState("ready"); }
      else setState("error");
    } catch {
      setState("error");
    }
  };

  return (
    <Panel
      title="Daily Brief"
      accent="hermes"
      icon={<Sunrise size={14} />}
      actions={brief ? <span className="pill pill-info">{brief.dateLabel}</span> : undefined}
    >
      {state === "loading" && (
        <div className="space-y-3" aria-label="Loading your brief">
          <div className="skeleton h-6 w-2/3" />
          <div className="skeleton h-4" />
          <div className="skeleton h-4 w-5/6" />
        </div>
      )}

      {(state === "empty" || state === "error" || state === "generating") && (
        <div className="py-5 text-center">
          <div
            className="mx-auto grid place-items-center w-11 h-11 rounded-full mb-3"
            style={{ background: "color-mix(in srgb, var(--gold) 10%, transparent)", color: "var(--gold)", border: "1px solid color-mix(in srgb, var(--gold) 25%, transparent)" }}
          >
            <Sunrise size={18} />
          </div>
          <p className="text-[13.5px]" style={{ color: "var(--cream-soft)" }}>
            {state === "error" ? "The brief could not be built just now." : "No brief yet."}
          </p>
          <p className="mt-1 text-[12px] leading-relaxed" style={{ color: "var(--cream-mute)" }}>
            Hermes reads your vault and writes a morning rundown: open tasks, what you touched, and a suggested focus.
          </p>
          <button
            onClick={generate}
            disabled={state === "generating"}
            className="copy-btn focus-ring mt-4 disabled:opacity-60"
          >
            {state === "generating" ? "Building your brief…" : state === "error" ? "Try again" : "Generate today's brief"}
          </button>
          {state === "generating" && (
            <p className="mt-2 text-[11px]" style={{ color: "var(--cream-mute)" }}>
              Reading your vault. This can take up to a minute.
            </p>
          )}
        </div>
      )}

      {state === "ready" && brief && (
        <div>
          <div className="hand text-[1.35rem] leading-none mb-2">{brief.greeting}</div>
          <h3 className="text-[17px] leading-snug" style={{ letterSpacing: "-0.015em" }}>{brief.headline}</h3>
          {brief.spoken && (
            <p className="mt-2.5 text-[13px] leading-[1.7]" style={{ color: "var(--cream-soft)" }}>
              {brief.spoken}
            </p>
          )}

          {brief.focus?.length > 0 && (
            <div className="mt-4">
              <div className="action-tag mb-2">Suggested focus</div>
              <ul className="space-y-1.5">
                {brief.focus.slice(0, MAX_FOCUS_SHOWN).map((f, i) => (
                  <li key={i} className="flex gap-2 text-[12.5px] leading-relaxed" style={{ color: "var(--cream)" }}>
                    <span aria-hidden style={{ color: "var(--gold)" }}>◆</span>
                    <span className="min-w-0">{f}</span>
                  </li>
                ))}
              </ul>
            </div>
          )}

          {brief.stats?.length > 0 && (
            <div className="mt-4 flex flex-wrap gap-2">
              {brief.stats.slice(0, 4).map((s, i) => (
                <span key={i} className="pill">{s.value} {s.label}</span>
              ))}
            </div>
          )}

          <Link
            href="/hermes?tab=apollo"
            className="focus-ring mt-5 inline-flex items-center gap-1 action-tag hover:opacity-100 transition-opacity"
            style={{ color: "var(--gold)", opacity: 0.85 }}
          >
            Open the full brief <ArrowUpRight size={12} />
          </Link>
        </div>
      )}
    </Panel>
  );
}
