"use client";

import Link from "next/link";
import { useEffect, useMemo, useState } from "react";
import { SendToBack } from "lucide-react";
import { AppShell } from "@/components/AppShell";
import { EmptyState, ErrorState, LoadingState } from "@/components/StateBlocks";
import { listRuns } from "@/lib/api/client";
import type { RunListItem } from "@/lib/api/types";
import { platformLabel } from "@/lib/flow-ledger/business";

function statusLabel(value?: string | null): string {
  const labels: Record<string, string> = {
    completed: "已完成",
    running: "运行中",
    failed: "运行失败",
    interrupted: "已中断",
    blocked: "已拦截",
    pending: "等待处理",
    success: "已完成",
    partial_success: "已完成"
  };
  return value ? labels[value] || "状态待确认" : "状态待确认";
}

function statusChipClass(value?: string | null): string {
  if (value === "failed" || value === "interrupted") return "red";
  if (value === "running" || value === "pending") return "blue";
  if (value === "blocked") return "yellow";
  return "green";
}

function formatBeijingTime(value?: string | null): string {
  if (!value) return "未记录时间";
  const iso = /z$|[+-]\d{2}:\d{2}$/i.test(value) ? value : `${value}Z`;
  const date = new Date(iso);
  if (Number.isNaN(date.getTime())) return "时间待确认";
  return `北京时间 ${new Intl.DateTimeFormat("zh-CN", {
    timeZone: "Asia/Shanghai",
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    hour12: false
  }).format(date)}`;
}

type DemandGroup = {
  key: string;
  id: number | null;
  name: string;
  runs: RunListItem[];
  latest: string;
};

const PLATFORM_ORDER = ["douyin", "kuaishou", "shipinhao"];

function platformsSorted(runs: RunListItem[]): string[] {
  const unique = [...new Set(runs.map((run) => run.platform || "unknown"))];
  return unique.sort((a, b) => {
    const ia = PLATFORM_ORDER.indexOf(a);
    const ib = PLATFORM_ORDER.indexOf(b);
    return (ia < 0 ? 99 : ia) - (ib < 0 ? 99 : ib);
  });
}

function byStartedDesc(a: RunListItem, b: RunListItem): number {
  return (b.started_at || "") > (a.started_at || "") ? 1 : (b.started_at || "") < (a.started_at || "") ? -1 : 0;
}

function buildDemands(runs: RunListItem[]): DemandGroup[] {
  const map = new Map<string, DemandGroup>();
  for (const run of runs) {
    const id = run.demand_content_id ?? null;
    const key = id != null ? `id:${id}` : "unknown";
    const name = run.demand_name || (id != null ? `需求 ${id}` : "未知需求");
    let group = map.get(key);
    if (!group) {
      group = { key, id, name, runs: [], latest: "" };
      map.set(key, group);
    }
    group.runs.push(run);
    if ((run.started_at || "") > group.latest) group.latest = run.started_at || "";
  }
  return [...map.values()].sort((a, b) => (b.latest > a.latest ? 1 : b.latest < a.latest ? -1 : 0));
}

export function RunListPage() {
  const [runs, setRuns] = useState<RunListItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [query, setQuery] = useState("");
  const [selectedKey, setSelectedKey] = useState<string | null>(null);

  async function load() {
    setLoading(true);
    setError(null);
    try {
      // 现规模(几十条 run)一次取够,前端按需求分组;>100 再加分页。
      const data = await listRuns(new URLSearchParams({ page_size: "100" }));
      setRuns(data.items || []);
    } catch (err) {
      setError(err instanceof Error ? err.message : String(err));
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    void load();
  }, []);

  const demands = useMemo(() => buildDemands(runs), [runs]);
  const filtered = useMemo(() => {
    const q = query.trim().toLowerCase();
    if (!q) return demands;
    return demands.filter((d) => d.name.toLowerCase().includes(q) || (d.id != null && String(d.id).includes(q)));
  }, [demands, query]);

  useEffect(() => {
    if (filtered.length && !filtered.some((d) => d.key === selectedKey)) {
      setSelectedKey(filtered[0].key);
    }
  }, [filtered, selectedKey]);

  const selected = demands.find((d) => d.key === selectedKey) || null;

  return (
    <AppShell
      title="按需求查看运行"
      subtitle="左侧选需求，右侧看它在各渠道的每一次运行"
      onRefresh={load}
      actions={
        <Link className="toolbar-button" href="/aigc-pushes">
          <SendToBack size={15} />
          推送 AIGC 记录
        </Link>
      }
    >
      {loading ? <LoadingState /> : null}
      {error ? <ErrorState message={error} /> : null}
      {!loading && !error && !runs.length ? <EmptyState label="暂无任务记录" /> : null}
      {runs.length ? (
        <div className="runs-by-demand">
          <aside className="rbd-demands">
            <input
              className="rbd-search"
              type="search"
              placeholder="搜索需求（名称 / ID）"
              value={query}
              onChange={(e) => setQuery(e.target.value)}
            />
            <div className="rbd-demand-list">
              {filtered.map((demand) => (
                <button
                  key={demand.key}
                  type="button"
                  className={`rbd-demand ${selected?.key === demand.key ? "active" : ""}`}
                  onClick={() => setSelectedKey(demand.key)}
                >
                  <strong>{demand.name}</strong>
                  <span className="rbd-demand-meta">
                    {demand.id != null ? `#${demand.id} · ` : ""}{demand.runs.length} 次运行
                  </span>
                  <span className="rbd-demand-platforms">
                    {platformsSorted(demand.runs).map((p) => (
                      <span className="chip" key={p}>{platformLabel(p)}</span>
                    ))}
                  </span>
                  <span className="rbd-demand-time">最新 {formatBeijingTime(demand.latest)}</span>
                </button>
              ))}
              {filtered.length === 0 ? <span className="muted">没有匹配的需求</span> : null}
            </div>
          </aside>

          <section className="rbd-runs">
            {selected ? (
              <>
                <div className="rbd-runs-head">
                  <strong>{selected.name}</strong>
                  <span className="muted">
                    {selected.id != null ? `需求 #${selected.id} · ` : ""}
                    {selected.runs.length} 次运行 · {platformsSorted(selected.runs).length} 个渠道
                  </span>
                </div>
                {platformsSorted(selected.runs).map((p) => {
                  const platformRuns = selected.runs.filter((r) => (r.platform || "unknown") === p).sort(byStartedDesc);
                  return (
                    <div className="rbd-platform" key={p}>
                      <div className="rbd-platform-head">
                        <span className="chip blue">{platformLabel(p)}</span>
                        <span className="muted">{platformRuns.length} 次运行</span>
                      </div>
                      <div className="rbd-run-list">
                        {platformRuns.map((run) => (
                          <Link className="rbd-run" href={`/runs/${encodeURIComponent(run.run_id)}`} key={run.run_id}>
                            <span className="rbd-run-time">{formatBeijingTime(run.started_at)}</span>
                            <span className={`chip ${statusChipClass(run.status)}`}>{statusLabel(run.status)}</span>
                            <span className="rbd-run-id muted">{run.run_id}</span>
                          </Link>
                        ))}
                      </div>
                    </div>
                  );
                })}
              </>
            ) : (
              <EmptyState label="选择左侧需求查看运行" />
            )}
          </section>
        </div>
      ) : null}
    </AppShell>
  );
}
