"use client";

import { useEffect, useMemo, useRef, useState } from "react";
import { readBackendUnavailableMessage, useResolvedApiBase } from "../lib/api-base";
import styles from "./report-print.module.css";

type ExecutorName = "browser" | "agent-s";
type TaskStatus = "enabled" | "disabled";
type RunStatus = "queued" | "running" | "success" | "failed" | "partial";

type ReportItem = {
  task: {
    id: string;
    name: string;
    siteUrl: string;
    cronExpr: string;
    serviceKey: string;
    preferredExecutor: ExecutorName;
    allowAgentFallback: boolean;
    status: TaskStatus;
    lastRunAt: string | null;
  };
  latestRun: {
    id: string;
    traceId: string;
    status: RunStatus;
    errorTag: string | null;
    failureReason: string | null;
    startedAt: string;
    endedAt: string | null;
    pageUrl: string | null;
    domSummary: string | null;
    executor: string;
    routePolicy: string | null;
    screenshots: string[];
    resultJsonUrl: string;
  } | null;
};

type InspectionReport = {
  generatedAt: string;
  reportDate: string;
  totalTasks: number;
  coveredTasks: number;
  successTasks: number;
  exceptionTasks: number;
  items: ReportItem[];
};

function formatTime(value?: string | null) {
  return value ? new Date(value).toLocaleString("zh-CN", { hour12: false }) : "暂无";
}

function executorLabel(value: string) {
  return value === "agent-s" ? "Agent-S" : "Browser";
}

function routePolicyLabel(value?: string | null) {
  return (
    ({
      "browser-first": "先 Browser 后 Agent-S",
      "browser-only": "仅 Browser",
      "agent-only": "仅 Agent-S",
    } as Record<string, string>)[value ?? ""] ?? "暂无"
  );
}

function statusLabel(status: RunStatus | "not-run") {
  return (
    ({
      queued: "排队中",
      running: "执行中",
      success: "成功",
      failed: "失败",
      partial: "部分成功",
      "not-run": "未执行",
    } as const)[status]
  );
}

function reportConclusion(item: ReportItem) {
  if (!item.latestRun) return "当日没有执行记录。";
  if (item.latestRun.status === "success") {
    return "本次巡检成功，页面可访问，且已留存截图。";
  }
  if (item.latestRun.status === "partial") {
    return `本次巡检存在异常，但已保留现场证据。${item.latestRun.failureReason ?? ""}`;
  }
  if (item.latestRun.status === "failed") {
    return `本次巡检失败。${item.latestRun.failureReason ?? "请结合执行证据继续排查。"}`;
  }
  return "任务仍在执行中。";
}

function readErrorMessage(error: unknown, apiBase?: string) {
  if (error instanceof TypeError) return readBackendUnavailableMessage(apiBase);
  if (error instanceof Error) return error.message;
  if (error && typeof error === "object" && "message" in error) {
    const message = (error as { message?: string | string[] }).message;
    return Array.isArray(message) ? message.join("；") : (message ?? "请求失败，请稍后重试。");
  }
  return "请求失败，请稍后重试。";
}

export function ReportPrint(props: {
  initialDate?: string;
  initialKeyword?: string;
  initialStatus?: string;
}) {
  const apiBase = useResolvedApiBase();
  const [report, setReport] = useState<InspectionReport | null>(null);
  const [errorMessage, setErrorMessage] = useState("");
  const [loading, setLoading] = useState(true);
  const printedRef = useRef(false);

  const reportDate = props.initialDate ?? new Date().toISOString().slice(0, 10);
  const keyword = (props.initialKeyword ?? "").trim();
  const status = props.initialStatus ?? "all";

  useEffect(() => {
    async function load() {
      const token = window.localStorage.getItem("sentai.token");
      if (!token) {
        setErrorMessage("当前没有可用登录会话，请先返回控制台登录后再打印报告。");
        setLoading(false);
        return;
      }

      setLoading(true);
      setErrorMessage("");
      try {
        const response = await fetch(`${apiBase}/api/runs/report?date=${reportDate}`, {
          cache: "no-store",
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${token}`,
          },
        });

        if (!response.ok) {
          let payload: unknown = null;
          try {
            payload = await response.json();
          } catch {
            payload = null;
          }
          throw new Error(readErrorMessage(payload, apiBase));
        }

        const payload = (await response.json()) as InspectionReport;
        setReport(payload);
      } catch (error) {
        setErrorMessage(readErrorMessage(error, apiBase));
      } finally {
        setLoading(false);
      }
    }

    void load();
  }, [apiBase, reportDate]);

  const filteredItems = useMemo(() => {
    if (!report) return [];
    return report.items.filter((item) => {
      const latestStatus = item.latestRun?.status ?? "not-run";
      const matchesKeyword =
        !keyword ||
        item.task.name.includes(keyword) ||
        item.task.siteUrl.includes(keyword) ||
        item.task.serviceKey.includes(keyword);
      const matchesStatus = status === "all" || latestStatus === status;
      return matchesKeyword && matchesStatus;
    });
  }, [keyword, report, status]);

  useEffect(() => {
    if (loading || errorMessage || !report || printedRef.current) return;
    printedRef.current = true;
    const timer = window.setTimeout(() => window.print(), 240);
    return () => window.clearTimeout(timer);
  }, [errorMessage, loading, report]);

  if (loading) {
    return (
      <main className={styles.page}>
        <section className={styles.loadingWrap}>
          <div className={styles.loadingCard}>
            <div className={styles.spinner} />
            <strong>正在生成打印视图</strong>
            <p className={styles.subtle}>系统正在整理报告数据与打印版排版，请稍候。</p>
          </div>
        </section>
      </main>
    );
  }

  if (errorMessage || !report) {
    return (
      <main className={styles.page}>
        <section className={styles.shell}>
          <section className={styles.toolbar}>
            <div className={styles.toolbarTitle}>
              <h1>巡检报告打印版</h1>
              <p>未能生成可打印报告。</p>
            </div>
            <div className={styles.buttonRow}>
              <button className={styles.buttonSecondary} onClick={() => window.close()} type="button">
                关闭
              </button>
            </div>
          </section>
          <section className={styles.banner}>
            <strong>生成失败</strong>
            <p className={styles.subtle}>{errorMessage || "报告数据为空。"}</p>
          </section>
        </section>
      </main>
    );
  }

  return (
    <main className={styles.page}>
      <section className={styles.shell}>
        <section className={styles.toolbar}>
          <div className={styles.toolbarTitle}>
            <h1>巡检报告打印版</h1>
            <p>
              报告日期：{reportDate} | 生成时间：{formatTime(report.generatedAt)} | 当前条目：
              {filteredItems.length}
            </p>
          </div>
          <div className={styles.buttonRow}>
            <button className={styles.button} onClick={() => window.print()} type="button">
              打印
            </button>
            <button className={styles.buttonSecondary} onClick={() => window.close()} type="button">
              关闭
            </button>
          </div>
        </section>

        <section className={styles.card}>
          <div className={styles.header}>
            <div className={styles.headerBlock}>
              <p className={styles.subtle}>SentAI Report</p>
              <h2 className={styles.title}>AI 智能巡检日报</h2>
            </div>
            <div className={styles.headerBlock}>
              <strong>筛选条件</strong>
              <p className={styles.meta}>关键词：{keyword || "无"}</p>
              <p className={styles.meta}>状态：{status === "all" ? "全部" : status}</p>
            </div>
          </div>
          <div className={styles.stats}>
            <article className={styles.stat}>
              <span className={styles.subtle}>任务总数</span>
              <strong>{report.totalTasks}</strong>
            </article>
            <article className={styles.stat}>
              <span className={styles.subtle}>当日已执行</span>
              <strong>{report.coveredTasks}</strong>
            </article>
            <article className={styles.stat}>
              <span className={styles.subtle}>成功任务</span>
              <strong>{report.successTasks}</strong>
            </article>
            <article className={styles.stat}>
              <span className={styles.subtle}>异常任务</span>
              <strong>{report.exceptionTasks}</strong>
            </article>
          </div>
        </section>

        <section className={styles.card}>
          <div className={styles.headerBlock}>
            <h2>报告项</h2>
            <p className={styles.subtle}>以下内容为打印专用排版，不再复用控制台页面结构。</p>
          </div>

          {filteredItems.length ? (
            <div className={styles.itemList}>
              {filteredItems.map((item) => {
                const latestStatus = item.latestRun?.status ?? "not-run";
                return (
                  <article className={styles.item} key={item.task.id}>
                    <div className={styles.itemTop}>
                      <div className={styles.itemTitle}>
                        <h3>{item.task.name}</h3>
                        <p className={styles.meta}>{item.task.siteUrl}</p>
                      </div>
                      <span className={styles.badge} data-status={latestStatus}>
                        {statusLabel(latestStatus)}
                      </span>
                    </div>

                    <p className={styles.summary}>{reportConclusion(item)}</p>

                    <div className={styles.metaGrid}>
                      <div className={styles.metaCell}>
                        <span>服务标识</span>
                        <strong>{item.task.serviceKey}</strong>
                      </div>
                      <div className={styles.metaCell}>
                        <span>首选执行器</span>
                        <strong>{executorLabel(item.task.preferredExecutor)}</strong>
                      </div>
                      <div className={styles.metaCell}>
                        <span>实际执行器</span>
                        <strong>{item.latestRun?.executor ?? "暂无"}</strong>
                      </div>
                      <div className={styles.metaCell}>
                        <span>路由策略</span>
                        <strong>{routePolicyLabel(item.latestRun?.routePolicy)}</strong>
                      </div>
                      <div className={styles.metaCell}>
                        <span>Trace ID</span>
                        <strong>{item.latestRun?.traceId ?? "暂无"}</strong>
                      </div>
                      <div className={styles.metaCell}>
                        <span>执行时间</span>
                        <strong>{formatTime(item.latestRun?.startedAt)}</strong>
                      </div>
                      <div className={styles.metaCell}>
                        <span>错误标签</span>
                        <strong>{item.latestRun?.errorTag ?? "无"}</strong>
                      </div>
                      <div className={styles.metaCell}>
                        <span>截图数量</span>
                        <strong>{item.latestRun?.screenshots.length ?? 0}</strong>
                      </div>
                    </div>
                  </article>
                );
              })}
            </div>
          ) : (
            <div className={styles.empty}>当前筛选条件下没有可打印的报告项。</div>
          )}
        </section>
      </section>
    </main>
  );
}
