import { useEffect, useMemo, useState } from "react";
import { Link } from "react-router-dom";
import { PageHeader } from "../components/layout/PageHeader";
import { Badge, Button, Card, EmptyState } from "../components/ui";
import { useData, useRepos } from "../data/DataContext";
import type {
  OutboxBundle,
  OwnPost,
  ScoutPost,
  ThreadsAccount,
  TrendItem,
} from "../domain/types";
import { useI18n } from "../i18n/I18nContext";
import { loadScoutToday } from "../lib/scoutToday";

function isPendingScout(p: ScoutPost): boolean {
  return p.outreach_status === "new" || p.outreach_status === "drafted";
}

function startOfLocalDayNano(): number {
  const d = new Date();
  d.setHours(0, 0, 0, 0);
  return d.getTime() * 1_000_000;
}

type AccountPulse = {
  account: ThreadsAccount;
  posts: number;
  views: number;
  likes: number;
  replies: number;
  topInsight?: string;
};

export function TodayPage() {
  const repos = useRepos();
  const { tick, refresh } = useData();
  const { t, locale } = useI18n();

  const [scoutPosts, setScoutPosts] = useState<ScoutPost[]>([]);
  const [outbox, setOutbox] = useState<OutboxBundle[]>([]);
  const [trends, setTrends] = useState<TrendItem[]>([]);
  const [ownPosts, setOwnPosts] = useState<OwnPost[]>([]);
  const [accounts, setAccounts] = useState<ThreadsAccount[]>([]);
  const [scoutDone, setScoutDone] = useState(0);
  const [scoutGoal, setScoutGoal] = useState(8);

  const dateLocale = locale === "en" ? "en-US" : "zh-TW";

  const todayLabel = useMemo(
    () =>
      new Date().toLocaleDateString(dateLocale, {
        month: "numeric",
        day: "numeric",
        weekday: "short",
      }),
    [dateLocale, tick],
  );

  useEffect(() => {
    void (async () => {
      const scout = loadScoutToday();
      setScoutDone(scout.done);
      setScoutGoal(scout.goalValue);
      const [posts, box, trendList, owns, acc] = await Promise.all([
        repos.scout.listPosts(),
        repos.outbox.list(),
        repos.inspiration.listTrends("all"),
        repos.ownPosts.list(),
        repos.accounts.list(),
      ]);
      setScoutPosts(posts);
      setOutbox(box);
      setTrends(trendList.slice(0, 8));
      setOwnPosts(owns);
      setAccounts(acc.filter((a) => a.is_usable));
    })();
  }, [repos, tick]);

  useEffect(() => {
    const onStore = () => refresh();
    window.addEventListener("harbor:store", onStore);
    return () => window.removeEventListener("harbor:store", onStore);
  }, [refresh]);

  const dayStart = useMemo(() => startOfLocalDayNano(), [tick]);

  const pendingScout = useMemo(
    () =>
      scoutPosts
        .filter(isPendingScout)
        .slice()
        .sort((a, b) => (b.score || 0) - (a.score || 0)),
    [scoutPosts],
  );

  const failedOutbox = useMemo(
    () => outbox.filter((o) => o.status === "partial_failed"),
    [outbox],
  );
  const runningOutbox = useMemo(
    () => outbox.filter((o) => o.status === "scheduling" || o.status === "active"),
    [outbox],
  );
  const sentToday = useMemo(() => {
    return outbox.filter((o) => {
      if (o.status !== "completed") return false;
      return o.updated_at >= dayStart;
    }).length;
  }, [outbox, dayStart]);

  const goalPct = Math.min(100, Math.round((scoutDone / Math.max(1, scoutGoal)) * 100));

  const topicCards = useMemo(() => trends.slice(0, 3), [trends]);

  const accountPulses = useMemo((): AccountPulse[] => {
    const byAcc = new Map<string, OwnPost[]>();
    for (const p of ownPosts) {
      const list = byAcc.get(p.account_id) || [];
      list.push(p);
      byAcc.set(p.account_id, list);
    }
    const rows: AccountPulse[] = [];
    for (const acc of accounts) {
      const posts = byAcc.get(acc.id) || [];
      if (!posts.length && accounts.length > 3) continue;
      const views = posts.reduce((s, p) => s + (p.view_count || 0), 0);
      const likes = posts.reduce((s, p) => s + (p.like_count || 0), 0);
      const replies = posts.reduce((s, p) => s + (p.reply_count || 0), 0);
      const top = posts.slice().sort((a, b) => (b.view_count || 0) - (a.view_count || 0))[0];
      rows.push({
        account: acc,
        posts: posts.length,
        views,
        likes,
        replies,
        topInsight: top?.insight || top?.formula_summary,
      });
    }
    // 沒 usable 時仍展示有貼文的帳
    if (!rows.length) {
      for (const [accId, posts] of byAcc) {
        const acc =
          accounts.find((a) => a.id === accId) ||
          ({
            id: accId,
            username: accId,
            display_name: accId,
            connection: "connected",
            is_usable: true,
            avatar_color: "#888",
          } as ThreadsAccount);
        rows.push({
          account: acc,
          posts: posts.length,
          views: posts.reduce((s, p) => s + (p.view_count || 0), 0),
          likes: posts.reduce((s, p) => s + (p.like_count || 0), 0),
          replies: posts.reduce((s, p) => s + (p.reply_count || 0), 0),
          topInsight: posts[0]?.insight,
        });
      }
    }
    return rows
      .sort((a, b) => b.views - a.views || b.likes - a.likes)
      .slice(0, 4);
  }, [accounts, ownPosts]);

  const pendingPreview = pendingScout.slice(0, 3);

  return (
    <>
      <PageHeader title={t("nav.today")} description={todayLabel} />

      <div className="hb-today-actions">
        <Link to="/app/studio">
          <Button type="button">{t("today.findTopic")}</Button>
        </Link>
        <Link to="/app/scout">
          <Button type="button" variant={pendingScout.length ? "primary" : "ghost"}>
            {pendingScout.length
              ? t("today.pendingRepliesN", { n: pendingScout.length })
              : t("today.pendingReplies")}
          </Button>
        </Link>
        <Link to="/app/studio/new">
          <Button type="button" variant="ghost">
            {t("today.newThread")}
          </Button>
        </Link>
      </div>

      {/* 數值列 */}
      <div className="hb-today-metrics" role="group" aria-label={t("today.metricsAria")}>
        <Link to="/app/scout" className="hb-today-metric">
          <span className="hb-today-metric__label">{t("today.metric.pending")}</span>
          <span className="hb-today-metric__value">{pendingScout.length}</span>
          <span className="hb-today-metric__hint">{t("today.metric.pendingHint")}</span>
        </Link>
        <div className="hb-today-metric">
          <span className="hb-today-metric__label">{t("today.metric.doneGoal")}</span>
          <span className="hb-today-metric__value">
            {scoutDone}
            <span className="hb-today-metric__den">/{scoutGoal}</span>
          </span>
          <div className="hb-progress hb-progress--sm" aria-hidden>
            <div className="hb-progress__bar" style={{ width: `${goalPct}%` }} />
          </div>
        </div>
        <Link to="/app/outbox" className="hb-today-metric">
          <span className="hb-today-metric__label">{t("today.metric.sentToday")}</span>
          <span className="hb-today-metric__value">{sentToday}</span>
          <span className="hb-today-metric__hint">
            {runningOutbox.length
              ? t("today.metric.running", { n: runningOutbox.length })
              : t("today.metric.sentDone")}
          </span>
        </Link>
        <Link
          to="/app/outbox"
          className={`hb-today-metric${failedOutbox.length ? " is-alert" : ""}`}
        >
          <span className="hb-today-metric__label">{t("today.metric.failed")}</span>
          <span className="hb-today-metric__value">{failedOutbox.length}</span>
          <span className="hb-today-metric__hint">
            {failedOutbox.length ? t("today.metric.needAction") : t("today.metric.ok")}
          </span>
        </Link>
      </div>

      {/* 待回覆 */}
      <Card title={t("today.pending.title", { n: pendingScout.length })}>
        {pendingPreview.length === 0 ? (
          <EmptyState
            title={t("today.pending.empty")}
            action={
              <Link to="/app/scout">
                <Button type="button">{t("today.goScout")}</Button>
              </Link>
            }
          />
        ) : (
          <div className="hb-stack">
            <ul className="hb-today-list">
              {pendingPreview.map((p) => (
                <li key={p.id}>
                  <Link to="/app/scout" className="hb-today-list__item">
                    <span className="hb-today-list__meta">
                      @{p.author}
                      {p.search_tag ? ` · ${p.search_tag}` : ""}
                      {typeof p.score === "number" ? ` · ${Math.round(p.score)}` : ""}
                    </span>
                    <span className="hb-today-list__text">
                      {p.text.slice(0, 96)}
                      {p.text.length > 96 ? "…" : ""}
                    </span>
                  </Link>
                </li>
              ))}
            </ul>
            {pendingScout.length > pendingPreview.length ? (
              <p className="text-muted" style={{ margin: 0, fontSize: "0.85rem" }}>
                {t("today.pending.more", { n: pendingScout.length - pendingPreview.length })}{" "}
                <Link to="/app/scout">{t("today.pending.handle")}</Link>
              </p>
            ) : (
              <Link to="/app/scout">
                <Button type="button" variant="ghost">
                  {t("today.pending.start")}
                </Button>
              </Link>
            )}
          </div>
        )}
      </Card>

      {/* 找話題 */}
      <Card title={t("today.topics.title")}>
        {topicCards.length === 0 ? (
          <EmptyState
            title={t("today.topics.empty")}
            action={
              <Link to="/app/studio">
                <Button type="button">{t("today.goStudio")}</Button>
              </Link>
            }
          />
        ) : (
          <div className="hb-stack">
            <ul className="hb-today-list">
              {topicCards.map((item) => (
                <li key={item.id}>
                  <Link to="/app/studio" className="hb-today-list__item">
                    <span className="hb-today-list__meta">
                      {item.label}
                      {typeof item.heat === "number" ? (
                        <Badge tone="brand">{t("today.heat", { n: item.heat })}</Badge>
                      ) : null}
                    </span>
                    <span className="hb-today-list__text">
                      {item.summary?.slice(0, 100) || item.samples?.[0] || t("today.topicAngle")}
                      {(item.summary?.length || 0) > 100 ? "…" : ""}
                    </span>
                  </Link>
                </li>
              ))}
            </ul>
            <div className="hb-today-actions" style={{ margin: 0 }}>
              <Link to="/app/studio">
                <Button type="button" variant="ghost">
                  {t("today.moreInspire")}
                </Button>
              </Link>
              <Link to="/app/studio/new">
                <Button type="button" variant="ghost">
                  {t("today.useTopic")}
                </Button>
              </Link>
            </div>
          </div>
        )}
      </Card>

      {/* 發送摘要 */}
      <Card title={t("today.outbox.title")}>
        {failedOutbox.length === 0 && runningOutbox.length === 0 && sentToday === 0 ? (
          <p className="text-muted" style={{ margin: 0 }}>
            {t("today.outbox.empty")}{" "}
            <Link to="/app/studio/new">{t("today.newThread")}</Link>
            {t("today.outbox.emptyMid")}{" "}
            <Link to="/app/outbox">{t("nav.outbox")}</Link>
            {t("today.outbox.emptyEnd")}
          </p>
        ) : (
          <div className="hb-stack" style={{ gap: "0.5rem" }}>
            <p style={{ margin: 0, fontSize: "0.9rem" }}>
              {t("today.outbox.summary", {
                sent: sentToday,
                running: runningOutbox.length,
                failed: failedOutbox.length,
              })}
            </p>
            {failedOutbox.slice(0, 2).map((o) => (
              <p key={o.id} style={{ margin: 0, fontSize: "0.85rem" }}>
                <Badge tone="danger">{t("today.badge.failed")}</Badge>{" "}
                <Link to={`/app/outbox/${o.id}`}>{o.title}</Link>
              </p>
            ))}
            {runningOutbox.slice(0, 2).map((o) => (
              <p key={o.id} style={{ margin: 0, fontSize: "0.85rem" }}>
                <Badge tone="brand">
                  {o.status === "scheduling" ? t("today.badge.scheduling") : t("today.badge.sending")}
                </Badge>{" "}
                <Link to={`/app/outbox/${o.id}`}>{o.title}</Link>
              </p>
            ))}
            <Link to="/app/outbox">
              <Button type="button" variant="ghost">
                {t("today.openOutbox")}
              </Button>
            </Link>
          </div>
        )}
      </Card>

      {/* 帳號成效（輕量） */}
      <Card title={t("today.accounts.title")}>
        {accountPulses.length === 0 ? (
          <EmptyState
            title={t("today.accounts.empty")}
            action={
              <Link to="/app/crew">
                <Button type="button" variant="ghost">
                  {t("nav.crew")}
                </Button>
              </Link>
            }
          />
        ) : (
          <div className="hb-stack">
            <ul className="hb-today-account-list">
              {accountPulses.map((row) => (
                <li key={row.account.id} className="hb-today-account">
                  <div className="hb-today-account__head">
                    <strong>@{row.account.username}</strong>
                    <span className="text-muted" style={{ fontSize: "0.78rem" }}>
                      {t("today.postsCount", { n: row.posts })}
                    </span>
                  </div>
                  <div className="hb-today-account__stats">
                    <span>
                      {t("today.views")} <strong>{row.views.toLocaleString(dateLocale)}</strong>
                    </span>
                    <span>
                      {t("today.likes")} <strong>{row.likes}</strong>
                    </span>
                    <span>
                      {t("today.repliesShort")} <strong>{row.replies}</strong>
                    </span>
                  </div>
                  {row.topInsight ? (
                    <p className="hb-today-account__insight">{row.topInsight}</p>
                  ) : null}
                </li>
              ))}
            </ul>
            <div className="hb-today-actions" style={{ margin: 0 }}>
              <Link to="/app/insights">
                <Button type="button">{t("today.fullInsights")}</Button>
              </Link>
              <Link to="/app/studio?tab=posts">
                <Button type="button" variant="ghost">
                  {t("today.viewPosts")}
                </Button>
              </Link>
              <Link to="/app/crew">
                <Button type="button" variant="ghost">
                  {t("today.manageAccounts")}
                </Button>
              </Link>
            </div>
          </div>
        )}
      </Card>
    </>
  );
}
