import type { ReactElement } from "react";
import { useMemo, useState } from "react";

import { filterGateRows, gatePayloadTone, gateStatusBadge, useGateDiagnostics } from "../../hooks/useGateDiagnostics";
import { formatBeijingTime, jsonPreview, toneClass } from "../../utils";
import { StateTag } from "../shared/StateTag";

export function GateView(): ReactElement {
  const { state, refresh } = useGateDiagnostics();
  const [statusFilter, setStatusFilter] = useState("all");
  const [search, setSearch] = useState("");
  const visibleRows = useMemo(() => filterGateRows(state.rows, statusFilter, search), [state.rows, statusFilter, search]);
  const tone = gatePayloadTone(state.payload, state.error);
  const summary = state.loading
    ? "读取 live 后端中"
    : state.payload
      ? `live 后端 ${visibleRows.length}/${state.rows.length} 行`
      : state.error
        ? "live 后端阻塞"
        : "等待 live 后端";
  return (
    <section className="view gate-view" id="gate" data-view="gate" aria-labelledby="gate-title">
      <header className="gate-header">
        <div>
          <p className="eyebrow">内部二级入口</p>
          <h2 id="gate-title">内部复核</h2>
        </div>
        <StateTag tone={toneClass(tone)} id="gate-source-status" title={state.error ?? (state.payload ? `route=${state.payload.route}; observedAt=${state.observedAt ?? state.payload.observedAt ?? "unknown"}` : "等待 /v1/diagnostics/gate")}>{summary}</StateTag>
      </header>
      <div className="gate-controls" aria-label="内部复核过滤控件">
        <label>
          <span>状态</span>
          <select id="gate-status-filter" value={statusFilter} onChange={(event) => setStatusFilter(event.currentTarget.value)}>
            <option value="all">全部</option>
            <option value="pass">通过</option>
            <option value="blocked">阻塞</option>
            <option value="fail">失败</option>
            <option value="warn">待验证</option>
            <option value="info">信息</option>
          </select>
        </label>
        <label>
          <span>搜索</span>
          <input id="gate-search" type="search" placeholder="按类别、检查项、对象或 trace 搜索" autoComplete="off" value={search} onChange={(event) => setSearch(event.currentTarget.value)} />
        </label>
        <button className="command-button secondary" id="gate-refresh" type="button" onClick={() => void refresh()} disabled={state.loading}>{state.loading ? "刷新中" : "刷新"}</button>
      </div>
      <div className="gate-table-wrap">
        <table className="gate-table" aria-describedby="gate-source-status">
          <thead>
            <tr>
              {["类别", "检查项", "状态", "归因对象", "关键细节", "证据/trace", "更新时间", "下一步"].map((head) => <th key={head}>{head}</th>)}
            </tr>
          </thead>
          <tbody id="gate-review-body">
            {state.loading && state.rows.length === 0 ? (
              <tr><td colSpan={8}>正在读取 live 后端聚合。</td></tr>
            ) : visibleRows.length === 0 ? (
              <tr><td colSpan={8}>没有匹配当前过滤条件的复核行。</td></tr>
            ) : (
              visibleRows.map((row, index) => {
                const badge = gateStatusBadge(row);
                return (
                  <tr key={`${row.check}-${index}`} data-status={row.status} data-status-key={row.statusKey}>
                    <td className="wrap">{row.category}</td>
                    <td className="wrap">{row.check}</td>
                    <td><StateTag tone={badge.tone} data-gate-row-status={row.statusKey}>{badge.label}</StateTag></td>
                    <td className="mono wrap">{row.owner}</td>
                    <td className="wrap">{row.detail}</td>
                    <td className="mono wrap">{row.evidence.join(" / ")}</td>
                    <td className="mono wrap">{formatBeijingTime(row.updatedAt, { withSeconds: true })}</td>
                    <td className="wrap">{row.next}</td>
                  </tr>
                );
              })
            )}
          </tbody>
        </table>
      </div>
      {state.rawResponse && !state.error ? (
        <details className="gate-raw" data-gate-raw>
          <summary>展开 gate 原始 JSON</summary>
          <pre>{jsonPreview(state.rawResponse, 2000)}</pre>
        </details>
      ) : null}
    </section>
  );
}
