/**
 * CRM 轉換統計三維（T591）：關鍵字／回覆版本／來源。
 * 樣本 < 5 只顯示絕對數。
 */
import { useCallback, useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { PageHeader } from "../components/layout/PageHeader";
import { EmptyState } from "../components/ui";
import { useRepos } from "../data/DataContext";
import type { CrmStats } from "../domain/types";
import { useI18n } from "../i18n/I18nContext";
import { useFormatApiError } from "../lib/apiErrors";
import "../styles/radar.css";

export function CrmStatsPage() {
  const { t } = useI18n();
  const repos = useRepos();
  const formatErr = useFormatApiError();
  const [stats, setStats] = useState<CrmStats | null>(null);
  const [err, setErr] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  // 後端未實作的維度要與「還沒有資料」分開顯示，否則會誤導使用者
  const unavailable = new Set(stats?.unavailable_dimensions ?? []);

  const load = useCallback(async () => {
    setStats(await repos.crm.getStats());
  }, [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

  return (
    <>
      <PageHeader title={t("crm.stats.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>
      </div>
      {err ? (
        <p className="hb-banner-error" role="alert">
          {err}
        </p>
      ) : null}
      {loading && !stats ? <p className="hb-radar-section__hint">{t("common.loading")}</p> : null}
      {stats ? (
        <section className="hb-radar-page">
          <div className="hb-radar-section">
            <h2 className="hb-radar-section__title">{t("crm.stats.terms")}</h2>
            {unavailable.has("terms") ? (
              <EmptyState title={t("crm.stats.unavailableDim")} />
            ) : stats.terms.length === 0 ? (
              <EmptyState title={t("crm.stats.emptyDim")} />
            ) : (
              <table className="hb-crm-stats-table">
                <thead>
                  <tr>
                    <th>{t("crm.stats.col.term")}</th>
                    <th>{t("crm.stats.col.accepted")}</th>
                    <th>{t("crm.stats.col.replied")}</th>
                    <th>{t("crm.stats.col.won")}</th>
                    <th>{t("crm.stats.col.rate")}</th>
                  </tr>
                </thead>
                <tbody>
                  {stats.terms.map((row) => (
                    <tr key={row.term}>
                      <td>{row.term}</td>
                      <td>{row.accepted}</td>
                      <td>{row.replied}</td>
                      <td>{row.won}</td>
                      <td className={row.insufficient_sample ? "is-insufficient" : undefined}>
                        {row.insufficient_sample
                          ? t("crm.stats.insufficient")
                          : row.conversion_rate != null
                            ? `${Math.round(row.conversion_rate * 100)}%`
                            : "—"}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            )}
          </div>

          <div className="hb-radar-section">
            <h2 className="hb-radar-section__title">{t("crm.stats.variants")}</h2>
            {unavailable.has("variants") ? (
              <EmptyState title={t("crm.stats.unavailableDim")} />
            ) : stats.variants.length === 0 ? (
              <EmptyState title={t("crm.stats.emptyDim")} />
            ) : (
              <table className="hb-crm-stats-table">
                <thead>
                  <tr>
                    <th>{t("crm.stats.col.variant")}</th>
                    <th>{t("crm.stats.col.used")}</th>
                    <th>{t("crm.stats.col.replied")}</th>
                    <th>{t("crm.stats.col.won")}</th>
                    <th>{t("crm.stats.col.rate")}</th>
                  </tr>
                </thead>
                <tbody>
                  {stats.variants.map((row) => (
                    <tr key={row.variant}>
                      <td>{row.variant}</td>
                      <td>{row.used}</td>
                      <td>{row.replied}</td>
                      <td>{row.won}</td>
                      <td className={row.insufficient_sample ? "is-insufficient" : undefined}>
                        {row.insufficient_sample
                          ? t("crm.stats.insufficient")
                          : row.success_rate != null
                            ? `${Math.round(row.success_rate * 100)}%`
                            : "—"}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            )}
          </div>

          <div className="hb-radar-section">
            <h2 className="hb-radar-section__title">{t("crm.stats.sources")}</h2>
            <table className="hb-crm-stats-table">
              <thead>
                <tr>
                  <th>{t("crm.stats.col.source")}</th>
                  <th>{t("crm.stats.col.won")}</th>
                </tr>
              </thead>
              <tbody>
                {stats.sources.map((row) => (
                  <tr key={row.source}>
                    <td>{row.source}</td>
                    <td className={row.insufficient_sample ? "is-insufficient" : undefined}>
                      {row.won}
                      {row.insufficient_sample ? ` · ${t("crm.stats.insufficient")}` : ""}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </section>
      ) : null}
    </>
  );
}
