import { useCallback, useEffect, useState } from "react";
import { PageHeader } from "../components/layout/PageHeader";
import { Card } from "../components/ui";
import { apiRequest } from "../data/live/http";
import { useI18n } from "../i18n/I18nContext";
import { InsightsPanel } from "./studio/InsightsPanel";

type Summary = {
  post_count: number;
  total_views: number;
  total_likes: number;
  total_replies: number;
  avg_eng_rate: number;
  conclusion: string;
  suggestions: string[];
  top_posts: { id: string; text_preview: string; eng_rate: number; view_count: number }[];
  month_buckets: { month_key: string; posts: number; views: number; avg_eng_rate: number }[];
};

/** 獨立路由 /app/insights：真同步資料摘要 + 既有面板 */
export function InsightsPage() {
  const { t } = useI18n();
  const [sum, setSum] = useState<Summary | null>(null);
  const [err, setErr] = useState("");

  const load = useCallback(async () => {
    try {
      setSum(await apiRequest<Summary>("/api/v1/insights/summary?months=3"));
    } catch (e) {
      setErr(e instanceof Error ? e.message : "load fail");
    }
  }, []);

  useEffect(() => {
    void load();
  }, [load]);

  return (
    <>
      <PageHeader title={t("insights.title")} />
      {err ? <p className="hb-form-error">{err}</p> : null}
      {sum ? (
        <Card title={t("insights.summaryTitle")} className="hb-stack" style={{ marginBottom: "1rem" }}>
          <p>{sum.conclusion}</p>
          <p className="text-muted">
            {t("insights.summaryStats", {
              posts: sum.post_count,
              views: sum.total_views,
              likes: sum.total_likes,
              replies: sum.total_replies,
              eng: (sum.avg_eng_rate * 100).toFixed(2),
            })}
          </p>
          <ul>
            {sum.suggestions.map((s) => (
              <li key={s}>{s}</li>
            ))}
          </ul>
          {sum.top_posts?.length ? (
            <div>
              <strong>{t("insights.summaryTop")}</strong>
              <ul>
                {sum.top_posts.map((p) => (
                  <li key={p.id}>
                    {t("insights.topPostLine", {
                      eng: (p.eng_rate * 100).toFixed(1),
                      views: p.view_count,
                      text: p.text_preview,
                    })}
                  </li>
                ))}
              </ul>
            </div>
          ) : null}
        </Card>
      ) : null}
      <InsightsPanel showTitle />
    </>
  );
}
