import { AppIcon } from "./PixelIcons";
import { Card, Tag } from "./ui";
import { TermHint } from "./TermHint";
import type { FundAnalysis, FundamentalsPayload } from "../lib/api";
import { fmtMoneyShort, fmtNum } from "../lib/stockTechnical";

function fmtMoneyTable(v: number | null | undefined) {
  if (v == null || Number.isNaN(v)) return "—";
  const a = Math.abs(v);
  if (a >= 1e9) return `$${(v / 1e9).toFixed(2)}B`;
  if (a >= 1e6) return `$${(v / 1e6).toFixed(1)}M`;
  return `$${v.toLocaleString(undefined, { maximumFractionDigits: 0 })}`;
}

function toneTag(tone?: string): "up" | "down" | "gold" {
  if (tone === "good") return "up";
  if (tone === "bad") return "down";
  return "gold";
}

function MetricCell({
  label,
  value,
  sub,
  tone,
}: {
  label: string;
  value: string;
  sub?: string | null;
  tone?: "up" | "down";
}) {
  return (
    <div className="fund-metric-cell">
      <span className="k">
        <TermHint term={label} />
      </span>
      <span className={`v ${tone || ""}`.trim()}>{value}</span>
      {sub ? <em className="sub">{sub}</em> : null}
    </div>
  );
}

type Props = {
  data?: FundamentalsPayload;
  aiFocus: { symbol: string; subPage: string; label: string; cardTitle?: string };
  onRefresh?: () => void;
  refreshing?: boolean;
};

export default function FundAnalysisPanel({ data, aiFocus, onRefresh, refreshing }: Props) {
  const analysis = data?.analysis;
  if (!analysis) return null;

  const cash = analysis.cash;
  const cv = analysis.capexVerdict;
  const bal = analysis.balanceInsight;
  const annual = data?.annual?.[0];
  const sectorNews = analysis.sectorNews;

  return (
    <>
      <div className="fund-layout-2">
        <Card
          className="fund-panel-compact"
          title="現金流解讀 · 錢花去哪"
          ico={<AppIcon name="coin" size={22} framed variant="hero" />}
          ai
          aiFocus={{ ...aiFocus, cardTitle: "現金流解讀" }}
          onRefresh={onRefresh}
          refreshing={refreshing}
        >
          <div className="fund-verdict-row">
            <Tag tone={toneTag(cv?.tone)}>{cv?.label || "分析中"}</Tag>
            <Tag tone={toneTag(cv?.worthBuy === "偏正面" ? "good" : cv?.worthBuy === "謹慎" ? "bad" : "gold")}>
              投資評價：{cv?.worthBuy || "—"}
            </Tag>
            {analysis.metrics?.fcfMargin != null ? (
              <span className="small muted">
                <TermHint term="FCF" /> {fmtNum(analysis.metrics.fcfMargin, 1)}%
              </span>
            ) : null}
          </div>

          <div className="fin-insight-list">
            <div className="fin-insight-item">
              <b>解讀</b> — {analysis.worthSummary || cv?.summary}
            </div>
            {analysis.bullets?.map((b, i) => (
              <div key={i} className="fin-insight-item">
                {b}
              </div>
            ))}
          </div>

          <div className="fund-metric-grid mt-s">
            <MetricCell
              label="營業現金流"
              value={fmtMoneyTable(cash?.ocf)}
              tone={cash?.ocf != null && cash.ocf >= 0 ? "up" : "down"}
            />
            <MetricCell label="資本支出 Capex" value={fmtMoneyTable(cash?.capex)} />
            <MetricCell
              label="自由現金流 FCF"
              value={fmtMoneyTable(cash?.fcf)}
              tone={cash?.fcf != null && cash.fcf >= 0 ? "up" : "down"}
            />
            <MetricCell label="投資活動" value={fmtMoneyTable(cash?.icf)} />
            <MetricCell label="融資活動" value={fmtMoneyTable(cash?.fincf)} />
            <MetricCell label="現金餘額" value={fmtMoneyTable(cash?.cash)} />
          </div>

          {cash?.uses?.length ? (
            <div className="fin-table-wrap fund-table-scroll mt-s">
              <table className="fin-table">
                <thead>
                  <tr>
                    <th>現金去向</th>
                    <th>金額</th>
                    <th>佔 OCF</th>
                  </tr>
                </thead>
                <tbody>
                  {cash.uses.map((u, i) => (
                    <tr key={i}>
                      <td className="fin-period">{u.label}</td>
                      <td>{fmtMoneyTable(u.amount)}</td>
                      <td>{u.pct != null ? `${fmtNum(u.pct, 0)}%` : "—"}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          ) : null}
        </Card>

        <Card
          className="fund-panel-compact"
          title="資產負債 · 投資痕跡"
          ico={<AppIcon name="macro" size={22} framed variant="hero" />}
          ai
          aiFocus={{ ...aiFocus, cardTitle: "資產負債投資痕跡" }}
          onRefresh={onRefresh}
          refreshing={refreshing}
        >
          <div className="fund-metric-grid">
            <MetricCell
              label="廠房設備 PPE"
              value={fmtMoneyTable(bal?.ppe)}
              sub={bal?.ppeGrowth != null ? `YoY ${fmtNum(bal.ppeGrowth, 0)}%` : null}
            />
            <MetricCell
              label="商譽 Goodwill"
              value={fmtMoneyTable(bal?.goodwill)}
              sub={bal?.goodwillGrowth != null ? `YoY ${fmtNum(bal.goodwillGrowth, 0)}%` : null}
            />
            <MetricCell label="存貨" value={fmtMoneyTable(bal?.inventory)} />
            <MetricCell label="應收帳款" value={fmtMoneyTable(bal?.receivables)} />
            <MetricCell label="總負債" value={fmtMoneyTable(data?.balance?.totalLiabilities as number)} />
            <MetricCell
              label="流動比率"
              value={bal?.currentRatio != null ? `${fmtNum(bal.currentRatio, 2)}x` : "—"}
            />
          </div>

          <div className="fin-insight-list">
            <div className="fin-insight-item">
              <b>怎麼看</b> —
              {bal?.ppeGrowth != null && bal.ppeGrowth > 10
                ? ` PPE 成長 ${fmtNum(bal.ppeGrowth, 0)}%，偏向投資產能／廠房設備。`
                : bal?.ppeGrowth != null && bal.ppeGrowth >= 0
                  ? " PPE 小幅成長，可能以維護性支出為主。"
                  : " PPE 變化不大或資料不足。"}
              {bal?.goodwillGrowth != null && bal.goodwillGrowth > 20
                ? ` 商譽大增 ${fmtNum(bal.goodwillGrowth, 0)}%，留意是否靠併購撐成長。`
                : ""}
              {analysis.metrics?.ocfToNetIncome != null && analysis.metrics.ocfToNetIncome < 80
                ? ` 營業現金流僅為淨利的 ${fmtNum(analysis.metrics.ocfToNetIncome, 0)}%，獲利含金量偏低。`
                : analysis.metrics?.ocfToNetIncome != null
                  ? ` 營業現金流約為淨利的 ${fmtNum(analysis.metrics.ocfToNetIncome, 0)}%，帳上獲利較有現金支撐。`
                  : ""}
            </div>
          </div>
        </Card>
      </div>

      {sectorNews ? (
        <Card
          className="mt"
          title="產業與市場消息 · 對本股的影響"
          ico={<AppIcon name="world" size={22} framed variant="hero" />}
          ai
          aiFocus={{ ...aiFocus, cardTitle: "產業市場消息" }}
          onRefresh={onRefresh}
          refreshing={refreshing}
        >
          {(sectorNews.sector || sectorNews.industry) ? (
            <p className="small muted" style={{ margin: "0 0 8px" }}>
              產業：{sectorNews.industry || "—"} · 板塊：{sectorNews.sector || "—"}
            </p>
          ) : null}
          {sectorNews.pulse ? <div className="sector-pulse">{sectorNews.pulse}</div> : null}
          <div className="fin-insight-item">{sectorNews.summary}</div>
          {sectorNews.items?.length ? (
            <div className="sector-news-list">
              {sectorNews.items.map((n, i) => (
                <div key={i} className="sector-news-item">
                  {n.url ? (
                    <a href={n.url} target="_blank" rel="noreferrer">
                      {n.title}
                    </a>
                  ) : (
                    <strong style={{ color: "var(--ink)", fontSize: 14 }}>{n.title}</strong>
                  )}
                  <div className="sector-news-meta">
                    {n.date ? <span>{n.date}</span> : null}
                    {n.source ? <span>{n.source}</span> : null}
                    <Tag tone={toneTag(n.impactTone)}>{n.impactLabel}</Tag>
                  </div>
                  <div className="sector-news-impact">{n.impactReason}</div>
                </div>
              ))}
            </div>
          ) : (
            <p className="small muted mt-s">近期無明顯產業關鍵字新聞；可至「新聞」分頁查看個股消息。</p>
          )}
        </Card>
      ) : null}

      {analysis.vendors?.vendors?.length ? (
        <Card
          className="mt"
          title="擴產時誰受益（上下游）"
          ico={<AppIcon name="world" size={22} framed variant="hero" />}
          ai
          aiFocus={{ ...aiFocus, cardTitle: "上下游受益" }}
          onRefresh={onRefresh}
          refreshing={refreshing}
        >
          <div className="fin-insight-item">{analysis.vendors.note}</div>
          <div className="intel-tags mt-s">
            {analysis.vendors.vendors.map((v) => (
              <Tag key={v} tone="cool">
                {v}
              </Tag>
            ))}
          </div>
          <div className="fin-insight-item mt-s">
            {annual?.capex != null && Math.abs(annual.capex) > 0
              ? `若 Capex ${fmtMoneyShort(Math.abs(annual.capex))} 用於擴產，設備商、代工與基建供應商通常最先受惠；擴產成功後則回饋下游客戶供貨能力。`
              : "Capex 資料不足，無法推估供應鏈受惠名單。"}
          </div>
        </Card>
      ) : null}

      {(data?.balanceHistory?.length || 0) > 1 ? (
        <Card
          className="mt"
          title="資產負債趨勢（近幾季）"
          ico={<AppIcon name="chart" size={22} framed variant="hero" />}
          ai
          aiFocus={{ ...aiFocus, cardTitle: "資產負債趨勢" }}
          onRefresh={onRefresh}
          refreshing={refreshing}
        >
          <div className="fin-table-wrap fund-table-scroll">
            <table className="fin-table fund-table-wide">
              <thead>
                <tr>
                  <th>期間</th>
                  <th>
                    <TermHint term="總資產" />
                  </th>
                  <th>
                    <TermHint term="現金餘額" />
                  </th>
                  <th>
                    <TermHint term="廠房設備 PPE" />
                  </th>
                  <th>
                    <TermHint term="負債比" />
                  </th>
                </tr>
              </thead>
              <tbody>
                {(data?.balanceHistory || []).map((b) => (
                  <tr key={b.end}>
                    <td className="fin-period">{b.end || "—"}</td>
                    <td>{fmtMoneyTable(b.totalAssets)}</td>
                    <td>{fmtMoneyTable(b.cash)}</td>
                    <td>{fmtMoneyTable(b.ppe)}</td>
                    <td>{b.debtToAssets != null ? `${fmtNum(b.debtToAssets, 1)}%` : "—"}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </Card>
      ) : null}
    </>
  );
}