"use client";

import { useState } from "react";
import PageHeader from "@/components/PageHeader";
import { api } from "@/lib/api";
import type { NewsArticle, NewsFeed } from "@/lib/types";
import { useApi } from "@/lib/useApi";

const TONE_STYLES: Record<NewsArticle["tone"], [string, string]> = {
  positive: ["bg-bull/15 text-bull", "▲ positive"],
  negative: ["bg-bear/15 text-bear", "▼ negative"],
  neutral: ["bg-ink-700 text-slate-400", "— neutral"],
};

function ToneChip({ tone }: { tone: NewsArticle["tone"] }) {
  const [cls, label] = TONE_STYLES[tone];
  return <span className={`px-2 py-0.5 rounded text-[11px] font-medium ${cls}`}>{label}</span>;
}

export default function NewsPage() {
  const [symbolInput, setSymbolInput] = useState("");
  const [activeSymbol, setActiveSymbol] = useState<string | undefined>(undefined);
  const [toneFilter, setToneFilter] = useState<"all" | NewsArticle["tone"]>("all");
  const { data, live, loading, refresh } = useApi<NewsFeed>(() => api.news(activeSymbol), 120_000);

  const articles = (data?.articles ?? []).filter(
    (a) => toneFilter === "all" || a.tone === toneFilter
  );

  const applySymbol = (s: string) => {
    const clean = s.trim().toUpperCase();
    setActiveSymbol(clean || undefined);
    setSymbolInput(clean);
    setTimeout(refresh, 0);
  };

  return (
    <div>
      <PageHeader
        title="Market News"
        subtitle="Headlines feeding the News Intelligence agent — tone tags are the same classification used in signal scoring"
        live={live}
        actions={
          <button
            onClick={refresh}
            className="text-xs px-3 py-1.5 rounded-lg border border-ink-600 text-slate-300 hover:bg-ink-800"
          >
            ↻ Refresh
          </button>
        }
      />

      <div className="flex flex-wrap items-center gap-3 mb-5">
        <form
          onSubmit={(e) => { e.preventDefault(); applySymbol(symbolInput); }}
          className="flex gap-2"
        >
          <input
            value={symbolInput}
            onChange={(e) => setSymbolInput(e.target.value)}
            placeholder="Filter by symbol (e.g. NVDA)"
            className="input-base w-52 uppercase"
            maxLength={12}
          />
          <button type="submit" className="text-xs px-4 rounded-lg bg-accent/15 border border-accent/40 text-accent hover:bg-accent/25">
            Filter
          </button>
          {activeSymbol && (
            <button
              type="button"
              onClick={() => applySymbol("")}
              className="text-xs px-3 rounded-lg border border-ink-600 text-slate-400 hover:bg-ink-800"
            >
              ✕ {activeSymbol}
            </button>
          )}
        </form>

        <div className="flex rounded-lg border border-ink-600 overflow-hidden text-xs">
          {(["all", "positive", "negative", "neutral"] as const).map((t) => (
            <button
              key={t}
              onClick={() => setToneFilter(t)}
              className={`px-3 py-2 capitalize ${
                toneFilter === t ? "bg-ink-700 text-slate-100" : "text-slate-400 hover:bg-ink-800"
              }`}
            >
              {t}
            </button>
          ))}
        </div>
      </div>

      {loading && !data ? (
        <div className="text-slate-500 animate-pulse">Loading news…</div>
      ) : articles.length === 0 ? (
        <div className="card p-6 text-sm text-slate-500">
          No articles match. {activeSymbol ? `Try clearing the ${activeSymbol} filter.` : "Try refreshing."}
        </div>
      ) : (
        <div className="space-y-3">
          {articles.map((a, i) => (
            <article key={i} className="card p-4">
              <div className="flex flex-wrap items-center gap-2 mb-2">
                {a.symbol && (
                  <button
                    onClick={() => applySymbol(a.symbol)}
                    className="px-2 py-0.5 rounded bg-ink-700 text-slate-200 text-xs font-mono font-semibold hover:bg-ink-600"
                  >
                    {a.symbol}
                  </button>
                )}
                <ToneChip tone={a.tone} />
                <span className="text-[11px] text-slate-500">
                  {a.source}{a.published ? ` · ${a.published}` : ""}
                </span>
              </div>
              <h3 className="text-sm font-semibold text-slate-100 leading-snug">
                {a.url ? (
                  <a href={a.url} target="_blank" rel="noopener noreferrer" className="hover:text-accent">
                    {a.headline} <span className="text-slate-500">↗</span>
                  </a>
                ) : (
                  a.headline
                )}
              </h3>
              {a.summary && <p className="text-xs text-slate-400 mt-1.5">{a.summary}</p>}
              {a.symbols.length > 1 && (
                <div className="mt-2 flex flex-wrap gap-1">
                  {a.symbols.slice(0, 6).map((s) => (
                    <button
                      key={s}
                      onClick={() => applySymbol(s)}
                      className="text-[10px] px-1.5 py-0.5 rounded bg-ink-850 border border-ink-700 text-slate-400 font-mono hover:text-slate-200"
                    >
                      {s}
                    </button>
                  ))}
                </div>
              )}
            </article>
          ))}
        </div>
      )}

      <p className="text-[11px] text-slate-600 mt-4">
        {live
          ? "Live headlines via Alpaca News API."
          : "Demo headlines — live articles appear automatically when the backend runs with your Alpaca keys."}{" "}
        Tone tags are transparent keyword classifications, not investment advice.
      </p>
    </div>
  );
}
