import { useEffect, useMemo, useState } from "react";
import { api, CapabilityData, JobRun, PostPerformance, PublishDashboardSummary, PublishHealth, ThreadsAccount } from "../api/haixun";
import { Badge, Card, ErrorText, PageTitle, QuickLinkCard, StatCard } from "../components/ui";
import { formatNano, shortText } from "../lib/format";
import { jobTemplateLabel } from "../lib/jobLabels";
import { jobStatusBadgeClass, jobStatusLabel } from "../lib/jobStatus";

export function DashboardPage({ navigate }: { navigate: (key: string) => void }) {
  const [caps, setCaps] = useState<CapabilityData>();
  const [accounts, setAccounts] = useState<ThreadsAccount[]>([]);
  const [health, setHealth] = useState<PublishHealth>();
  const [performance, setPerformance] = useState<PostPerformance>();
  const [summary, setSummary] = useState<PublishDashboardSummary>();
  const [jobs, setJobs] = useState<JobRun[]>([]);
  const [error, setError] = useState<unknown>();

  useEffect(() => {
    let alive = true;
    async function load() {
      try {
        const [capData, accountData, jobData, summaryData] = await Promise.all([api.capabilities(), api.threadsAccounts(), api.jobs(), api.publishDashboardSummary()]);
        if (!alive) return;
        setCaps(capData);
        setAccounts(accountData.list || []);
        setJobs(jobData.list || []);
        setSummary(summaryData);
        const active = capData.active_threads_account_id || accountData.active_account_id || accountData.list?.[0]?.id;
        if (active) {
          const [healthData, perfData] = await Promise.all([api.publishHealth(active), api.postPerformance(active)]);
          if (!alive) return;
          setHealth(healthData);
          setPerformance(perfData);
        }
      } catch (err) {
        if (alive) setError(err);
      }
    }
    void load();
    return () => {
      alive = false;
    };
  }, []);

  const analysis = useMemo(() => buildPerformanceAnalysis(health, performance), [health, performance]);

  return (
    <div className="page-grid">
      <PageTitle title="總覽" subtitle="確認能力、檢查發文庫存，並快速看最近 Threads 成效。" />
      <ErrorText error={error} />
      <div className="grid-3">
        <StatCard label="探索能力" value={caps?.discover_ready ? "Ready" : "未完成"} hint={caps?.discover_hint || "搜尋來源與帳號設定"} />
        <StatCard label="AI 能力" value={caps?.ai_ready ? "Ready" : "未完成"} hint={caps?.ai_hint || "研究/文案 provider"} />
        <StatCard label="發文能力" value={caps?.publish_ready ? "Ready" : "未完成"} hint={caps?.publish_hint || "Threads API 連線"} />
      </div>

      <div className="grid-2">
        <Card title="營運快照">
          <div className="page-grid">
            <div className="button-row">
              <Badge variant="brand">帳號 {accounts.length}</Badge>
              <Badge variant={summary?.total_failed ? "danger" : "success"}>失敗 {summary?.total_failed ?? 0}</Badge>
              <Badge variant="warning">待發 {summary?.total_pending ?? 0}</Badge>
            </div>
            <p className="muted">
              近 7 天發布 {summary?.total_published_7d ?? health?.summary.published_7d ?? 0} 篇，累積 {summary?.total_likes_7d ?? health?.summary.total_likes_7d ?? 0} 讚、{summary?.total_replies_7d ?? health?.summary.total_replies_7d ?? 0} 則回覆。
            </p>
          </div>
        </Card>

        <Card title="最近任務">
          <div className="page-grid">
            {jobs.slice(0, 5).map((job) => (
              <div key={job.id} className="button-row" style={{ justifyContent: "space-between" }}>
                <span>{jobTemplateLabel(job.template_type)}</span>
                <Badge variant={jobStatusBadgeClass(job.status)}>{jobStatusLabel(job.status)}</Badge>
              </div>
            ))}
            {jobs.length === 0 ? <p className="muted">目前沒有任務。</p> : null}
          </div>
        </Card>
      </div>

      <Card title="多帳號營運">
        <div className="table-wrap">
          <table>
            <thead>
              <tr>
                <th>帳號</th>
                <th>待發</th>
                <th>7D 發布</th>
                <th>互動</th>
                <th>推薦時段</th>
                <th>狀態</th>
              </tr>
            </thead>
            <tbody>
              {summary?.list?.map((item) => (
                <tr key={item.account_id}>
                  <td><strong>{item.account_name}</strong></td>
                  <td>{item.pending_scheduled}</td>
                  <td>{item.published_7d}</td>
                  <td>讚 {item.total_likes_7d} / 回覆 {item.total_replies_7d}</td>
                  <td>{item.best_slot || "資料不足"}</td>
                  <td><Badge variant={item.paused ? "warning" : item.failed_count ? "danger" : "success"}>{item.paused ? "暫停" : item.failed_count ? "需檢查" : "正常"}</Badge></td>
                </tr>
              ))}
            </tbody>
          </table>
          {!summary?.list?.length ? <p className="muted">還沒有帳號 summary。</p> : null}
        </div>
      </Card>

      <Card title="成效分析">
        <div className="grid-3">
          <StatCard label="近 7 天互動" value={analysis.totalEngagement} hint={`平均每篇 ${analysis.avgEngagement} 次互動`} />
          <StatCard label="讚 / 回覆比例" value={`${analysis.likeShare}% / ${analysis.replyShare}%`} hint="觀察內容是否只被看見，還是有引發對話" />
          <StatCard label="健康分數" value={`${analysis.healthScore}/100`} hint={analysis.healthHint} />
        </div>
        <div className="grid-2" style={{ marginTop: "1rem" }}>
          <div className="card">
            <div className="button-row" style={{ justifyContent: "space-between" }}>
              <strong>互動組成</strong>
              <Badge variant="brand">7D</Badge>
            </div>
            <StackedBar
              segments={[
                { label: "讚", value: analysis.totalLikes, color: "var(--hx-brand)" },
                { label: "回覆", value: analysis.totalReplies, color: "var(--hx-warning)" },
                { label: "轉發/引用", value: analysis.totalAmplify, color: "var(--hx-success)" }
              ]}
            />
          </div>
          <div className="card">
            <div className="button-row" style={{ justifyContent: "space-between" }}>
              <strong>Checkpoint 趨勢</strong>
              <Badge variant={analysis.checkpointPoints.length ? "success" : "neutral"}>{analysis.checkpointPoints.length ? "已追蹤" : "資料不足"}</Badge>
            </div>
            <LineChart points={analysis.checkpointPoints} />
          </div>
        </div>
      </Card>

      <div className="grid-2">
        <Card title="Top 發文">
          <div className="page-grid">
            {analysis.topPosts.map((post, index) => (
              <HorizontalBar
                key={post.id}
                rank={index + 1}
                label={post.label}
                value={post.value}
                max={analysis.topPostMax}
                meta={`讚 ${post.likes} / 回覆 ${post.replies}`}
              />
            ))}
            {analysis.topPosts.length === 0 ? <p className="muted">還沒有足夠的發文成效資料。</p> : null}
          </div>
        </Card>

        <Card title="營運提示">
          <div className="page-grid">
            {analysis.insights.map((item) => (
              <div key={item} className="button-row">
                <Badge variant="brand">Insight</Badge>
                <span>{item}</span>
              </div>
            ))}
          </div>
        </Card>
      </div>

      <Card title="下一步">
        <div className="grid-3">
          <QuickLinkCard title="連接 Threads 帳號" desc="OAuth、AI key、發文設定集中管理。" onClick={() => navigate("accounts")} />
          <QuickLinkCard title="管理已發貼文" desc="回留言、看成效、AI 覆盤爆款公式。" onClick={() => navigate("publish")} />
          <QuickLinkCard title="文案任務" desc="直接寫、貼文改寫、話題矩陣都在這裡。" onClick={() => navigate("missions")} />
          <QuickLinkCard title="開始找 TA" desc="建立主題、用 AI prompt 產生詳細研究地圖 + 三層知識圖譜，找出適合置入的討論。" onClick={() => navigate("patrol")} />
        </div>
      </Card>

      <Card title="最近發布">
        <div className="page-grid">
          {health?.list?.slice(0, 5).map((item) => (
            <div key={item.media_id}>
              <strong>{shortText(item.text || item.media_id, 110)}</strong>
              <div className="muted">發布：{formatNano(item.published_at)}，讚 {item.like_count}，回覆 {item.reply_count}</div>
            </div>
          ))}
          {!health?.list?.length ? <p className="muted">還沒有可追蹤的發文。</p> : null}
        </div>
      </Card>
    </div>
  );
}

type Segment = {
  label: string;
  value: number;
  color: string;
};

type ChartPoint = {
  label: string;
  value: number;
};

function buildPerformanceAnalysis(health?: PublishHealth, performance?: PostPerformance) {
  const posts = health?.list || [];
  const perfPosts = performance?.posts || [];
  const totalLikes = health?.summary.total_likes_7d ?? posts.reduce((sum, post) => sum + post.like_count, 0);
  const totalReplies = health?.summary.total_replies_7d ?? posts.reduce((sum, post) => sum + post.reply_count, 0);
  const totalAmplify = posts.reduce((sum, post) => sum + (post.repost_count || 0) + (post.quote_count || 0) + (post.shares || 0), 0);
  const totalEngagement = totalLikes + totalReplies + totalAmplify;
  const published = Math.max(health?.summary.published_7d || posts.length, 0);
  const avgEngagement = published > 0 ? Math.round(totalEngagement / published) : 0;
  const likeShare = totalEngagement > 0 ? Math.round((totalLikes / totalEngagement) * 100) : 0;
  const replyShare = totalEngagement > 0 ? Math.round((totalReplies / totalEngagement) * 100) : 0;
  const failed = health?.summary.failed_count || 0;
  const pending = health?.summary.pending_scheduled || 0;
  const healthScore = clamp(Math.round(65 + Math.min(avgEngagement, 20) + Math.min(pending, 10) - failed * 12), 0, 100);
  const healthHint = failed > 0 ? "有失敗項目，建議先檢查 token 或 queue" : pending < 3 ? "庫存偏低，建議補內容" : "發文管線穩定";

  const topPosts = posts
    .map((post) => ({
      id: post.media_id,
      label: shortText(post.text || post.media_id, 54),
      likes: post.like_count,
      replies: post.reply_count,
      value: post.like_count + post.reply_count + (post.repost_count || 0) + (post.quote_count || 0)
    }))
    .sort((a, b) => b.value - a.value)
    .slice(0, 5);

  const checkpointMap = new Map<string, number>();
  for (const post of posts) {
    for (const checkpoint of post.checkpoints || []) {
      checkpointMap.set(checkpoint.checkpoint, (checkpointMap.get(checkpoint.checkpoint) || 0) + checkpoint.like_count + checkpoint.reply_count);
    }
  }
  const checkpointPoints = Array.from(checkpointMap.entries()).map(([label, value]) => ({ label, value }));
  const topPostMax = Math.max(...topPosts.map((post) => post.value), 1);

  const insights = [
    totalEngagement === 0 ? "目前互動資料不足，先累積 3 到 5 篇發布後再看趨勢。" : `最近互動以「讚」為主，占 ${likeShare}%；若想拉高對話，可增加提問型 CTA。`,
    failed > 0 ? `有 ${failed} 個發文失敗，先到發文中心檢查錯誤原因。` : "目前沒有發文失敗紀錄，排程管線看起來穩定。",
    pending < 3 ? `待發庫存只有 ${pending} 篇，建議先補到至少 3 篇以上。` : `待發庫存 ${pending} 篇，短期內容供給足夠。`,
    perfPosts.length > 0 ? `Threads API 最近回傳 ${perfPosts.length} 篇貼文成效，可用來回填最佳發文時段。` : "尚未讀到即時 post performance，OAuth/API 權限可再檢查一次。"
  ];

  return {
    totalLikes,
    totalReplies,
    totalAmplify,
    totalEngagement,
    avgEngagement,
    likeShare,
    replyShare,
    healthScore,
    healthHint,
    topPosts,
    topPostMax,
    checkpointPoints,
    insights
  };
}

function StackedBar({ segments }: { segments: Segment[] }) {
  const total = segments.reduce((sum, item) => sum + item.value, 0);
  return (
    <div className="page-grid" style={{ gap: "0.65rem", marginTop: "0.8rem" }}>
      <div style={{ display: "flex", height: "1rem", overflow: "hidden", borderRadius: "999px", background: "var(--hx-surface-muted)" }}>
        {segments.map((segment) => (
          <div
            key={segment.label}
            style={{
              width: `${total > 0 ? Math.max((segment.value / total) * 100, segment.value ? 8 : 0) : 0}%`,
              background: segment.color
            }}
          />
        ))}
      </div>
      <div className="button-row">
        {segments.map((segment) => (
          <span key={segment.label} className="badge badge-neutral">
            <span style={{ width: 8, height: 8, borderRadius: 99, background: segment.color }} />
            {segment.label} {segment.value}
          </span>
        ))}
      </div>
    </div>
  );
}

function LineChart({ points }: { points: ChartPoint[] }) {
  if (points.length === 0) {
    return <p className="muted">等待 publish analytics checkpoints 回填後會顯示趨勢。</p>;
  }
  const width = 420;
  const height = 150;
  const max = Math.max(...points.map((point) => point.value), 1);
  const path = points
    .map((point, index) => {
      const x = points.length === 1 ? width / 2 : (index / (points.length - 1)) * width;
      const y = height - (point.value / max) * (height - 24) - 12;
      return `${index === 0 ? "M" : "L"}${x},${y}`;
    })
    .join(" ");

  return (
    <div>
      <svg viewBox={`0 0 ${width} ${height}`} style={{ width: "100%", height: "10rem", overflow: "visible" }} role="img" aria-label="checkpoint 成效趨勢">
        <path d={path} fill="none" stroke="var(--hx-brand)" strokeWidth="4" strokeLinecap="round" strokeLinejoin="round" />
        {points.map((point, index) => {
          const x = points.length === 1 ? width / 2 : (index / (points.length - 1)) * width;
          const y = height - (point.value / max) * (height - 24) - 12;
          return <circle key={point.label} cx={x} cy={y} r="5" fill="var(--hx-brand)" />;
        })}
      </svg>
      <div className="button-row" style={{ justifyContent: "space-between" }}>
        {points.map((point) => (
          <span key={point.label} className="subtle" style={{ fontSize: "0.8rem" }}>{point.label}: {point.value}</span>
        ))}
      </div>
    </div>
  );
}

function HorizontalBar({ rank, label, value, max, meta }: { rank: number; label: string; value: number; max: number; meta: string }) {
  return (
    <div>
      <div className="button-row" style={{ justifyContent: "space-between" }}>
        <strong>{rank}. {label}</strong>
        <Badge variant="brand">{value}</Badge>
      </div>
      <div style={{ height: "0.7rem", borderRadius: "999px", background: "var(--hx-surface-muted)", overflow: "hidden", margin: "0.35rem 0" }}>
        <div style={{ width: `${Math.max((value / max) * 100, 4)}%`, height: "100%", background: "linear-gradient(90deg, var(--hx-brand), var(--hx-glow))" }} />
      </div>
      <div className="subtle" style={{ fontSize: "0.82rem" }}>{meta}</div>
    </div>
  );
}

function clamp(value: number, min: number, max: number) {
  return Math.min(max, Math.max(min, value));
}
