import React from "react";
import { fmtClock, fmtDate } from "./time";
import { LoadingTitle } from "./loading-indicator";
import { errorMessage, requestJson } from "./unidesk-error";
import { UniDeskErrorBanner } from "./unidesk-error-banner";

type AnyRecord = Record<string, any>;

const h = React.createElement;
const { useEffect } = React;
const useState: any = React.useState;


function StatusBadge({ status, children }: AnyRecord) {
  const normalized = String(status || "unknown").toLowerCase();
  return h("span", { className: `status-badge ${normalized}` }, children || status || "unknown");
}

function MetricCard({ label, value, hint, tone }: AnyRecord) {
  return h("article", { className: `metric-card ${tone || ""}` },
    h("div", { className: "metric-label" }, label),
    h("div", { className: "metric-value" }, value),
    h("div", { className: "metric-hint" }, hint),
  );
}

function Panel({ title, eyebrow, actions, children, className, loading }: AnyRecord) {
  return h("section", { className: `panel ${className || ""}` },
    h("div", { className: "panel-head" },
      h("div", null,
        eyebrow ? h("p", { className: "panel-eyebrow" }, eyebrow) : null,
        h(LoadingTitle, { title, loading }),
      ),
      actions ? h("div", { className: "panel-actions" }, actions) : null,
    ),
    h("div", { className: "panel-body" }, children),
  );
}

function RawButton({ title, data, onOpen, testId }: AnyRecord) {
  return h("button", {
    type: "button",
    className: "ghost-btn",
    "data-testid": testId,
    onClick: () => onOpen(title, data),
  }, "查看原始JSON");
}

function EmptyState({ title, text }: AnyRecord) {
  return h("div", { className: "empty-state" }, h("strong", null, title), h("span", null, text));
}

function microserviceRuntime(service: any): AnyRecord {
  return service?.runtime && typeof service.runtime === "object" && !Array.isArray(service.runtime) ? service.runtime : {};
}

function microserviceBackend(service: any): AnyRecord {
  return service?.backend && typeof service.backend === "object" && !Array.isArray(service.backend) ? service.backend : {};
}

function microserviceRepository(service: any): AnyRecord {
  return service?.repository && typeof service.repository === "object" && !Array.isArray(service.repository) ? service.repository : {};
}

function findjobSummaryMetric(summary: any, key: string): string {
  const value = summary && typeof summary === "object" ? summary[key] : undefined;
  return Number.isFinite(Number(value)) ? String(value) : "--";
}

function findjobJobRows(data: any): any[] {
  const rows = Array.isArray(data?.jobs) ? data.jobs : [];
  return rows.slice(0, 40);
}

function findjobDraftRows(data: any): any[] {
  const rows = Array.isArray(data?.drafts) ? data.drafts : [];
  return rows.slice(0, 12);
}

export function FindJobPage({ microservices, onRaw, apiBaseUrl = "/api" }: AnyRecord) {
  const service = microservices.find((item: any) => item.id === "findjob") || null;
  const [state, setState] = useState({ loading: false, error: "", health: null, summary: null, jobs: null, drafts: null, refreshedAt: null });

  async function load(): Promise<void> {
    if (!service) return;
    setState((prev: any) => ({ ...prev, loading: true, error: "" }));
    try {
      const [health, summary, jobs, drafts] = await Promise.all([
        requestJson(`${apiBaseUrl}/microservices/findjob/health`),
        requestJson(`${apiBaseUrl}/microservices/findjob/proxy/api/summary`),
        requestJson(`${apiBaseUrl}/microservices/findjob/proxy/api/jobs?__unideskArrayLimit=jobs:40`),
        requestJson(`${apiBaseUrl}/microservices/findjob/proxy/api/drafts`),
      ]);
      setState({ loading: false, error: "", health, summary, jobs, drafts, refreshedAt: new Date() });
    } catch (err) {
      setState((prev: any) => ({ ...prev, loading: false, error: errorMessage(err, "FindJob 加载失败") }));
    }
  }

  useEffect(() => {
    load();
  }, [service?.id, service?.runtime?.providerStatus]);

  if (!service) return h(EmptyState, { title: "FindJob 未登记", text: "请在 config.json 的 microservices 中登记用户服务 id=findjob" });

  const runtime = microserviceRuntime(service);
  const repository = microserviceRepository(service);
  const backend = microserviceBackend(service);
  const summary = state.summary || {};
  const jobs = findjobJobRows(state.jobs);
  const drafts = findjobDraftRows(state.drafts);
  const transform = state.jobs?._unidesk?.arrayLimits?.jobs;
  return h("div", { className: "findjob-page", "data-testid": "findjob-page" },
    h(Panel, {
      title: "FindJob 工作台",
      eyebrow: "D601 用户服务",
      loading: state.loading,
      actions: h("div", { className: "panel-actions" },
        h("button", { type: "button", className: "ghost-btn", onClick: load, disabled: state.loading, "data-testid": "findjob-refresh-button" }, state.loading ? "刷新中" : "刷新"),
        h(RawButton, { title: "FindJob 用户服务", data: service, onOpen: onRaw, testId: "raw-findjob-service" }),
      ),
    },
      h("div", { className: "findjob-hero" },
        h("div", null,
          h("div", { className: "node-version-line" },
            h(StatusBadge, { status: runtime.providerStatus === "online" ? "online" : "warn" }, runtime.providerStatus || "unknown"),
            h("span", null, service.providerId),
            h("span", null, backend.public ? "公网暴露" : "仅 UniDesk frontend 代理访问"),
          ),
          h("p", { className: "muted paragraph" }, service.description),
        ),
        h("div", { className: "microservice-ref-card" },
          h("span", null, "Repo"),
          h("strong", null, repository.url || "--"),
          h("code", null, repository.commitId || "--"),
        ),
        h("div", { className: "microservice-ref-card" },
          h("span", null, "D601 Docker"),
          h("strong", null, `${backend.nodeBindHost || "--"}:${backend.nodePort || "--"}`),
          h("code", null, `${repository.composeFile || "--"} / ${repository.composeService || "--"}`),
        ),
      ),
      h(UniDeskErrorBanner, { error: state.error, wide: true }),
    ),
    h("div", { className: "findjob-grid" },
      h(Panel, { title: "岗位指标", eyebrow: state.refreshedAt ? `Updated ${fmtClock(state.refreshedAt)}` : "Summary", loading: state.loading },
        h("div", { className: "metric-grid" },
          h(MetricCard, { label: "岗位总量", value: findjobSummaryMetric(summary, "totalJobs"), hint: "tracked jobs", tone: "ok" }),
          h(MetricCard, { label: "原始岗位", value: findjobSummaryMetric(summary, "rawJobs"), hint: "raw queue" }),
          h(MetricCard, { label: "已验证", value: findjobSummaryMetric(summary, "verifiedJobs"), hint: "verified set" }),
          h(MetricCard, { label: "优先处理", value: findjobSummaryMetric(summary, "prioritizedJobs"), hint: "prioritized" }),
          h(MetricCard, { label: "过期", value: findjobSummaryMetric(summary, "staleJobs"), hint: "stale jobs", tone: "warn" }),
          h(MetricCard, { label: "无效", value: findjobSummaryMetric(summary, "invalidJobs"), hint: "invalid jobs", tone: "warn" }),
          h(MetricCard, { label: "上海", value: findjobSummaryMetric(summary, "shanghaiJobs"), hint: "city filter" }),
          h(MetricCard, { label: "Health", value: state.health?.ok ? "OK" : "--", hint: "D601 /api/health" }),
        ),
        h("div", { className: "panel-actions inline-actions" }, h(RawButton, { title: "FindJob Summary", data: summary, onOpen: onRaw, testId: "raw-findjob-summary" })),
      ),
      h(Panel, { title: "近期岗位", eyebrow: transform ? `${transform.returnedLength}/${transform.originalLength} Preview` : `${jobs.length} Preview`, loading: state.loading },
        jobs.length === 0 ? h(EmptyState, { title: "暂无岗位预览", text: "等待 D601 findjob backend 返回 /api/jobs" }) :
          h("div", { className: "table-wrap findjob-job-table" }, h("table", null,
            h("thead", null, h("tr", null, h("th", null, "优先级"), h("th", null, "状态"), h("th", null, "单位"), h("th", null, "职位"), h("th", null, "城市"), h("th", null, "阶段"), h("th", null, "截止"), h("th", null, "证据"))),
            h("tbody", null, jobs.map((job: any) => h("tr", { key: job.id },
              h("td", null, h(StatusBadge, { status: String(job.priority || "").toLowerCase() || "unknown" }, job.priority || "--")),
              h("td", null, h(StatusBadge, { status: String(job.status || "").toLowerCase() || "unknown" }, job.status || "--")),
              h("td", null, job.organization_name || "--", h("code", null, job.id || "--")),
              h("td", null, job.display_title || job.title || "--"),
              h("td", null, job.display_city || job.city || "--"),
              h("td", null, job.workflow_stage || "--"),
              h("td", null, job.deadline || "--"),
              h("td", null, job.evidence_url ? h("a", { href: job.evidence_url, target: "_blank", rel: "noreferrer" }, "打开") : h("span", { className: "muted" }, "无")),
            ))),
          )),
        h("div", { className: "panel-actions inline-actions" }, h(RawButton, { title: "FindJob Jobs Preview", data: state.jobs, onOpen: onRaw, testId: "raw-findjob-jobs" })),
      ),
      h(Panel, { title: "草稿与报告", eyebrow: `${drafts.length} Drafts`, loading: state.loading },
        drafts.length === 0 ? h(EmptyState, { title: "暂无草稿", text: "D601 findjob backend 未返回 drafts" }) :
          h("div", { className: "draft-list" }, drafts.map((draft: any) => h("article", { key: draft.id, className: "draft-card" },
            h("div", { className: "node-card-head" }, h("strong", null, draft.id), h(StatusBadge, { status: draft.status }, draft.status || "--")),
            h("div", { className: "docker-meta compact" },
              h("span", null, draft.workflow_stage || "--"),
              h("span", null, `jobs ${draft.counts?.jobs ?? 0}`),
              h("span", null, `reports ${draft.counts?.reports ?? 0}`),
            ),
            h("span", null, draft.latestReportPath || "暂无报告"),
            h("code", null, fmtDate(draft.updated_at || draft.updatedAt)),
          ))),
        h("div", { className: "panel-actions inline-actions" }, h(RawButton, { title: "FindJob Drafts", data: state.drafts, onOpen: onRaw, testId: "raw-findjob-drafts" })),
      ),
    ),
  );
}
