import { useMemo, useState } from "react";
import AiSummaryCard from "./AiSummaryCard";
import { AppIcon } from "./PixelIcons";
import { Card, Tag, Loading, RefreshButton } from "./ui";
import type { CompanyIntelPayload, HoldersPayload, SecArchivePayload } from "../lib/api";
import {
  entityLabel,
  interpretCompanyProfile,
  interpretFilings,
  interpretInsiders,
  insiderSignalLabel,
  secArchiveLocalUrl,
} from "../lib/companyInterpret";
import { fmtNum } from "../lib/stockTechnical";

type ChainGroup = { label?: string; entities?: (string | { name?: string; symbol?: string })[]; note?: string };

function fmtShares(n: number | null | undefined) {
  if (n == null || Number.isNaN(n)) return "—";
  const a = Math.abs(n);
  const s = n < 0 ? "-" : "";
  if (a >= 1e6) return `${s}${(a / 1e6).toFixed(2)}M`;
  if (a >= 1e3) return `${s}${(a / 1e3).toFixed(1)}K`;
  return `${s}${a.toLocaleString()}`;
}

function chainColHtml(groups: ChainGroup[] | undefined) {
  if (!groups?.length) return <p className="muted small">尚無資料，可按「強制更新」請 AI 整理。</p>;
  return (
    <ul className="chain-entity-list">
      {groups.map((g, i) => (
        <li key={i}>
          <strong>{g.label || "環節"}</strong>
          <span>{(g.entities || []).map(entityLabel).join("、 ") || "待查證"}</span>
          {g.note ? <em className="chain-note">{g.note}</em> : null}
        </li>
      ))}
    </ul>
  );
}

function impactTone(impact?: string): "up" | "down" | "gold" {
  if (impact === "positive") return "up";
  if (impact === "negative") return "down";
  return "gold";
}

type Props = {
  symbol: string;
  intel?: CompanyIntelPayload;
  intelLoading?: boolean;
  secArchive?: SecArchivePayload;
  secLoading?: boolean;
  holders?: HoldersPayload;
  syncingIntel?: boolean;
  syncingSec?: boolean;
  onSyncIntel: (force?: boolean) => void;
  onReloadIntel?: () => void;
  intelReloading?: boolean;
  onSyncSec: (force?: boolean) => void;
  aiFocus: { symbol: string; subPage: string; label: string; cardTitle?: string };
};

export default function CompanyIntelPanel({
  symbol,
  intel,
  intelLoading,
  secArchive,
  secLoading,
  holders,
  syncingIntel,
  syncingSec,
  onSyncIntel,
  onReloadIntel,
  intelReloading,
  onSyncSec,
  aiFocus,
}: Props) {
  const [newsTab, setNewsTab] = useState<"tw" | "global">("tw");

  const insiderInterp = useMemo(() => interpretInsiders(intel?.insiders), [intel?.insiders]);
  const filingInterp = useMemo(() => interpretFilings(secArchive?.filings), [secArchive?.filings]);
  const profileInterp = useMemo(() => interpretCompanyProfile(intel, symbol), [intel, symbol]);

  const profileDesc = intel?.profileZh?.description || intel?.management?.longBusinessSummary;
  const officers = intel?.management?.officers || [];
  const chain = intel?.industryChain || {};
  const mgmtBrief = intel?.managementBrief || [];
  const newsTw = intel?.newsTw || [];
  const newsGlobal = intel?.newsGlobal || [];
  const filings = secArchive?.filings || [];
  const earnings = secArchive?.earnings || [];
  const syncNote = intel?.nextPublicLabel || intel?.syncSkipReason || (intel?.enrichedAt ? `上次整理 ${intel.enrichedAt.slice(0, 16).replace("T", " ")}` : "");

  if (intelLoading && !intel) return <Loading />;

  return (
    <div className="backpack-panel company-intel-panel">
      <div className="intel-sync-bar">
        <span className="small muted">
          {syncingIntel ? "正在同步公司研究資料…" : syncNote}
          {intel?.aiEnriched ? " · AI 已整理" : ""}
        </span>
        <span className="intel-sync-actions">
          {onReloadIntel ? (
            <RefreshButton onClick={onReloadIntel} loading={intelReloading} label="重新載入" />
          ) : null}
          <button type="button" className="btn-ghost" disabled={syncingIntel} onClick={() => onSyncIntel(true)}>
            {syncingIntel ? "更新中…" : "強制更新"}
          </button>
        </span>
      </div>

      {(intel?.dataHealth?.notes || []).length ? (
        <ul className="intel-health-notes">
          {intel!.dataHealth!.notes!.map((n, i) => (
            <li key={i}>{n}</li>
          ))}
        </ul>
      ) : null}

      <AiSummaryCard symbol={symbol} scope="company" title="AI 公司總結（MCP + 今日快取）" aiFocus={aiFocus} />

      <Card className="mt" title="公司介紹" ico={<AppIcon name="world" size={22} framed variant="hero" />} ai aiFocus={{ ...aiFocus, cardTitle: "公司介紹" }}>
        <div className="intel-tags">
          {intel?.management?.sector ? <Tag tone="cool">{intel.management.sector}</Tag> : null}
          {intel?.management?.industry ? <Tag tone="gold">{intel.management.industry}</Tag> : null}
          {intel?.profileZh?.businessModel ? <Tag tone="gold">{intel.profileZh.businessModel}</Tag> : null}
        </div>
        <p className="company-blurb">{profileDesc || "尚無公司簡介，請按「強制更新」。"}</p>
        <div className="interpret-box">
          <div className="interpret-label">解讀</div>
          <p>{profileInterp}</p>
        </div>
        {intel?.management?.website ? (
          <p className="small muted mt-s">
            <a href={intel.management.website} target="_blank" rel="noopener noreferrer">
              官網
            </a>
          </p>
        ) : null}
      </Card>

      <Card className="mt" title="產業上下游" ico={<AppIcon name="compass" size={22} framed variant="hero" />} ai aiFocus={{ ...aiFocus, cardTitle: "產業鏈" }}>
        <div className="chain-map">
          <div className="chain-col chain-col--up">
            <b>上游 · 供應商</b>
            {chainColHtml(chain.upstreamDetail || chain.upstream?.map((u: string) => ({ label: u, entities: [u] })))}
          </div>
          <div className="chain-col chain-col--down">
            <b>下游 · 誰買他們的產品</b>
            {chainColHtml(chain.downstreamDetail || chain.downstream?.map((d: string) => ({ label: d, entities: [d] })))}
          </div>
        </div>
        {chain.tenKExcerpt ? (
          <p className="chain-excerpt small muted mt-s">
            <b>10-K 摘錄：</b>
            {chain.tenKExcerpt}
            {chain.tenKExcerpt.length >= 400 ? "…" : ""}
          </p>
        ) : null}
        {(intel?.resources || []).length ? (
          <div className="intel-resource-links mt-s">
            {(intel?.resources || []).slice(0, 6).map((r, i) => (
              <a key={i} href={r.url} target="_blank" rel="noopener noreferrer">
                {r.labelZh || r.label || "連結"}
              </a>
            ))}
          </div>
        ) : null}
      </Card>

      <Card className="mt" title="經營管理層" ico={<AppIcon name="scroll" size={22} framed variant="hero" />} ai aiFocus={{ ...aiFocus, cardTitle: "管理層" }}>
        <p className="small muted">來源：{intel?.management?.source || "Yahoo / SEC"}</p>
        {officers.length ? (
          <div className="officer-grid">
            {officers.map((o) => (
              <div key={o.name} className="officer-card">
                <b>{o.name}</b>
                <span>{o.titleDisplay || o.titleZh || o.title || ""}</span>
                {o.totalPay != null ? <small>總薪酬 ${fmtNum(o.totalPay / 1e6, 1)}M</small> : null}
              </div>
            ))}
          </div>
        ) : (
          <p className="muted">管理層名單載入中或未取得，請按「強制更新」。</p>
        )}
      </Card>

      <Card className="mt" title="內部人持股／賣股" ico={<AppIcon name="cards" size={22} framed variant="hero" />} ai aiFocus={{ ...aiFocus, cardTitle: "內部人交易" }}>
        {holders?.breakdown?.insidersPct != null ? (
          <p className="small muted mb-s">流通持股中內部人約 {fmtNum(holders.breakdown.insidersPct, 1)}%（Yahoo 統計）</p>
        ) : null}
        <div className="insider-summary">
          <div className={insiderInterp.acquiredCount ? "good" : ""}>
            <b>{insiderInterp.acquiredCount}</b>
            <span>近期偏買進</span>
          </div>
          <div className={insiderInterp.disposedCount ? "bad" : ""}>
            <b>{insiderInterp.disposedCount}</b>
            <span>近期偏賣出</span>
          </div>
        </div>
        <div className="interpret-box">
          <div className="interpret-label">解讀</div>
          <p className={insiderInterp.tone}>{insiderInterp.summary}</p>
          {insiderInterp.bullets.length ? (
            <ul className="interpret-bullets">
              {insiderInterp.bullets.map((b, i) => (
                <li key={i}>{b}</li>
              ))}
            </ul>
          ) : null}
        </div>
        <p className="small muted">SEC Form 4：A＝取得、D＝處分。美股才有申報；台股請搭配籌碼分頁。</p>
        {intel?.insiders?.length ? (
          <div className="insider-tx-grid">
            {intel.insiders.map((t, i) => {
              const sig = insiderSignalLabel(t);
              return (
                <a
                  key={i}
                  className={`insider-row insider-row--${sig.tone}`}
                  href={t.url || "#"}
                  target="_blank"
                  rel="noopener noreferrer"
                  onClick={(e) => !t.url && e.preventDefault()}
                >
                  <div>
                    <b>{t.owner || "內部人"}</b>
                    <span>{t.title || ""}</span>
                  </div>
                  <div>
                    <b className={sig.tone}>{sig.label}</b>
                    <span>{t.reportDate || t.filingDate || ""}</span>
                  </div>
                  <div>
                    <b>
                      {fmtShares(t.acquired)} / {fmtShares(t.disposed)}
                    </b>
                    <span>取得 / 處分</span>
                  </div>
                </a>
              );
            })}
          </div>
        ) : (
          <p className="muted">近期沒有抓到 Form 4 申報。</p>
        )}
        {(holders?.insiders || []).length ? (
          <div className="mt-s">
            <h4 className="small" style={{ color: "var(--gold-soft)" }}>
              主要內部人持股（Yahoo）
            </h4>
            <ul className="insider-holder-list">
              {holders!.insiders!.slice(0, 8).map((h, i) => (
                <li key={i}>
                  {h.name}
                  {h.relation ? ` · ${h.relation}` : ""}
                  {h.pctHeld != null ? ` · ${fmtNum(h.pctHeld, 2)}%` : ""}
                  {h.shares != null ? ` · ${fmtShares(h.shares)} 股` : ""}
                </li>
              ))}
            </ul>
          </div>
        ) : null}
      </Card>

      <Card className="mt" title="經營層動態" ico={<AppIcon name="calendar" size={22} framed variant="hero" />} ai aiFocus={{ ...aiFocus, cardTitle: "經營層動態" }}>
        {mgmtBrief.length ? (
          <div className="mgmt-brief-list">
            {mgmtBrief.map((m, i) => (
              <div key={i} className={`mgmt-brief-row mgmt-brief--${impactTone(m.impact)}`}>
                <div>
                  <b>{m.headline}</b>
                  <small>
                    {m.date || ""} · {m.source || ""}
                  </small>
                </div>
                <p>{m.summary}</p>
                {m.url ? (
                  <a href={m.url} target="_blank" rel="noopener noreferrer">
                    原文
                  </a>
                ) : null}
              </div>
            ))}
          </div>
        ) : (
          <p className="muted">尚無管理層相關新聞摘要。</p>
        )}
      </Card>

      <Card
        className="mt"
        title="重要申報與財報（10-K / 10-Q）"
        ico={<AppIcon name="scroll" size={22} framed variant="hero" />}
        ai
        aiFocus={{ ...aiFocus, cardTitle: "SEC 申報" }}
        onRefresh={() => onSyncSec(false)}
        refreshing={secLoading}
        refreshLabel="重新整理清單"
      >
        <div className="interpret-box">
          <div className="interpret-label">解讀</div>
          <p>{filingInterp.summary}</p>
          {filingInterp.bullets.length ? (
            <ul className="interpret-bullets">
              {filingInterp.bullets.map((b, i) => (
                <li key={i}>{b}</li>
              ))}
            </ul>
          ) : null}
        </div>
        <div className="sec-archive-actions">
          <button type="button" className="btn-primary" disabled={syncingSec} onClick={() => onSyncSec(true)}>
            {syncingSec ? "封存中…" : "抓取並封存到本機"}
          </button>

          <span className="small muted">
            {secArchive?.meta?.lastSyncAt
              ? `已封存 ${filings.length} 筆 · 上次 ${new Date(secArchive.meta.lastSyncAt).toLocaleString("zh-TW")}`
              : filings.length
                ? `本機 ${filings.length} 筆`
                : "尚未同步"}
          </span>
        </div>
        {secLoading && !filings.length ? <Loading /> : null}
        <div className="sec-archive-block mt-s">
          <h4>SEC 重要申報</h4>
          <div className="sec-filing-list">
            {filings.length ? (
              filings.map((f) => {
                const local = f.localPrimary || f.localTxt;
                const localUrl = secArchiveLocalUrl(symbol, f.accession, local);
                return (
                  <div key={f.accession} className={`sec-filing-row${f.isEarningsRelated ? " sec-filing-row--earn" : ""}`}>
                    <div className="sec-filing-main">
                      <b>
                        {f.formZh || f.form}
                        <span className="sec-filing-form">{f.form}</span>
                      </b>
                      <small>
                        申報 {f.filedDate || "—"}
                        {f.reportDate && f.reportDate !== f.filedDate ? ` · 報告日 ${f.reportDate}` : ""}
                      </small>
                      {f.description ? <p>{String(f.description).slice(0, 160)}</p> : null}
                      {f.excerpt ? <p className="sec-filing-excerpt">{f.excerpt.slice(0, 280)}…</p> : null}
                    </div>
                    <div className="sec-filing-links">
                      {localUrl ? (
                        <a className="btn-ghost" href={localUrl} target="_blank" rel="noopener noreferrer">
                          本機已存
                        </a>
                      ) : (
                        <span className="sec-missing">未下載</span>
                      )}
                      {f.url ? (
                        <a href={f.url} target="_blank" rel="noopener noreferrer">
                          SEC 線上
                        </a>
                      ) : null}
                    </div>
                  </div>
                );
              })
            ) : (
              <p className="muted">尚無封存申報。美股可按上方按鈕從 SEC 下載。</p>
            )}
          </div>
        </div>
        {earnings.length ? (
          <div className="sec-archive-block mt">
            <h4>財報日與法說相關</h4>
            <div className="sec-earn-list">
              {earnings.slice(0, 8).map((e, i) => (
                <div key={i} className="sec-earn-row">
                  <div>
                    <b>{e.titleZh || e.title}</b>
                    <small>
                      {e.eventDate || ""} {e.timeLabel || ""} · {e.source || ""}
                    </small>
                  </div>
                  {e.note ? <p>{String(e.note).slice(0, 200)}</p> : null}
                  <div className="sec-filing-links">
                    {e.url ? (
                      <a href={e.url} target="_blank" rel="noopener noreferrer">
                        連結
                      </a>
                    ) : null}
                    {e.transcriptSearchUrl ? (
                      <a href={e.transcriptSearchUrl} target="_blank" rel="noopener noreferrer">
                        投資人關係
                      </a>
                    ) : null}
                  </div>
                </div>
              ))}
            </div>
          </div>
        ) : null}
      </Card>

      <Card
        className="mt"
        title="相關新聞"
        ico={<AppIcon name="calendar" size={22} framed variant="hero" />}
        ai
        aiFocus={{ ...aiFocus, cardTitle: "公司新聞" }}
        onRefresh={onReloadIntel}
        refreshing={intelReloading}
      >
        <div className="news-tabs">
          <button type="button" className={`news-tab ${newsTab === "tw" ? "active" : ""}`} onClick={() => setNewsTab("tw")}>
            台灣 ({newsTw.length})
          </button>
          <button type="button" className={`news-tab ${newsTab === "global" ? "active" : ""}`} onClick={() => setNewsTab("global")}>
            國際 ({newsGlobal.length})
          </button>
        </div>
        <NewsPanel items={newsTab === "tw" ? newsTw : newsGlobal} />
      </Card>
    </div>
  );
}

function NewsPanel({ items }: { items: { title?: string; titleZh?: string; link?: string; url?: string; source?: string; publisher?: string; publishedAt?: string }[] }) {
  if (!items.length) return <p className="muted mt-s">暫無新聞</p>;
  return (
    <ul className="news-list mt-s">
      {items.map((n, i) => {
        const href = n.link || n.url;
        const title = n.titleZh || n.title;
        return (
          <li key={i}>
            {href ? (
              <a href={href} target="_blank" rel="noopener noreferrer">
                {title}
              </a>
            ) : (
              <span>{title}</span>
            )}
            <span className="news-meta">
              {n.source || n.publisher ? `${n.source || n.publisher} · ` : ""}
              {n.publishedAt ? n.publishedAt.slice(0, 16).replace("T", " ") : ""}
            </span>
          </li>
        );
      })}
    </ul>
  );
}