/**
 * 待追蹤收件匣（T591）＋簡易轉換統計入口。
 */
import { useCallback, useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { PageHeader } from "../components/layout/PageHeader";
import { Badge, Button, EmptyState } from "../components/ui";
import { useRepos } from "../data/DataContext";
import type { FollowUp } from "../domain/types";
import { useI18n } from "../i18n/I18nContext";
import { useFormatApiError } from "../lib/apiErrors";
import { formatLocalDateTime } from "../lib/time";
import "../styles/radar.css";

export function CrmFollowUpsPage() {
  const { t } = useI18n();
  const repos = useRepos();
  const formatErr = useFormatApiError();
  const [list, setList] = useState<FollowUp[]>([]);
  const [err, setErr] = useState<string | null>(null);
  const [msg, setMsg] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const [busy, setBusy] = useState("");
  const [drafts, setDrafts] = useState<Record<string, string>>({});

  const load = useCallback(async () => {
    const res = await repos.crm.listFollowUps(1, 50);
    setList(res.list);
  }, [repos.crm]);

  useEffect(() => {
    let alive = true;
    setLoading(true);
    load()
      .then(() => {
        if (alive) setErr(null);
      })
      .catch((e) => {
        if (alive) setErr(formatErr(e));
      })
      .finally(() => {
        if (alive) setLoading(false);
      });
    return () => {
      alive = false;
    };
  }, [load]); // eslint-disable-line react-hooks/exhaustive-deps

  async function run(key: string, action: () => Promise<void>, ok?: string) {
    setBusy(key);
    setErr(null);
    setMsg(null);
    try {
      await action();
      await load();
      if (ok) setMsg(ok);
    } catch (e) {
      setErr(formatErr(e));
    } finally {
      setBusy("");
    }
  }

  return (
    <>
      <PageHeader title={t("crm.followups.title")} />
      <div className="hb-radar-actions hb-radar-actions--toolbar">
        <Link className="hb-btn hb-btn--secondary" to="/app/crm">
          {t("crm.followups.link.board")}
        </Link>
        <Link className="hb-btn hb-btn--ghost" to="/app/crm/stats">
          {t("crm.followups.link.stats")}
        </Link>
      </div>

      {err ? (
        <p className="hb-banner-error" role="alert">
          {err}
        </p>
      ) : null}
      {msg ? (
        <p className="hb-banner-ok" role="status">
          {msg}
        </p>
      ) : null}

      {loading && !list.length ? <p className="hb-radar-section__hint">{t("common.loading")}</p> : null}

      {!loading && list.length === 0 ? (
        <EmptyState title={t("crm.followups.empty")} description={t("crm.followups.emptyHint")} />
      ) : (
        <ul className="radar-list">
          {list.map((f) => {
            const overdue = f.due_at < Date.now() * 1e6 && f.status !== "done";
            const handle = f.contact?.author_handle || f.contact_id;
            return (
              <li
                key={f.id}
                className={`hb-followup-row${overdue ? " hb-followup-row--overdue" : ""}`}
              >
                <div>
                  <strong>@{handle}</strong>
                  <div className="hb-opp-card__meta">
                    <Badge tone={f.status === "escalated" ? "danger" : "neutral"}>
                      {t(`crm.followups.status.${f.status}`)}
                    </Badge>
                    {f.contact?.stage ? (
                      <span>{t(`crm.stage.${f.contact.stage}`)}</span>
                    ) : null}
                    <span>
                      {t("crm.followups.due")}: {formatLocalDateTime(f.due_at)}
                    </span>
                  </div>
                  {drafts[f.id] ? <pre className="radar-card__reply">{drafts[f.id]}</pre> : null}
                  {f.status === "escalated" ? (
                    <p className="hb-radar-section__hint">{t("crm.followups.escalatedHint")}</p>
                  ) : null}
                </div>
                <div className="hb-radar-actions">
                  <Link className="hb-btn hb-btn--ghost" to={`/app/crm?contact=${encodeURIComponent(f.contact_id)}`}>
                    {t("crm.followups.openContact")}
                  </Link>
                  <Button
                    type="button"
                    variant="secondary"
                    disabled={busy === `msg-${f.id}`}
                    onClick={() =>
                      void run(`msg-${f.id}`, async () => {
                        const text = await repos.crm.generateFollowUpMessage(f.id);
                        setDrafts((m) => ({ ...m, [f.id]: text }));
                      }, t("crm.followups.msg.drafted"))
                    }
                  >
                    {t("crm.followups.aiMessage")}
                  </Button>
                  {drafts[f.id] ? (
                    <Button
                      type="button"
                      variant="ghost"
                      onClick={() => void navigator.clipboard.writeText(drafts[f.id])}
                    >
                      {t("radar.today.reply.copy")}
                    </Button>
                  ) : null}
                  <Button
                    type="button"
                    disabled={busy === `done-${f.id}`}
                    onClick={() =>
                      void run(`done-${f.id}`, async () => {
                        await repos.crm.doneFollowUp(f.id);
                      }, t("crm.followups.msg.done"))
                    }
                  >
                    {t("crm.followups.done")}
                  </Button>
                  <Button
                    type="button"
                    variant="ghost"
                    disabled={busy === `snooze-${f.id}`}
                    onClick={() =>
                      void run(`snooze-${f.id}`, async () => {
                        await repos.crm.snoozeFollowUp(f.id, 3);
                      }, t("crm.followups.msg.snoozed"))
                    }
                  >
                    {t("crm.followups.snooze")}
                  </Button>
                </div>
              </li>
            );
          })}
        </ul>
      )}
    </>
  );
}
