// =============================================================================
// WOOO AIOps - AwoooP M7 審批佇列頁面
// =============================================================================
// 每 10 秒自動刷新，timeout < 5 分鐘時紅色高亮警示

"use client";

import { useState, useEffect, useCallback, useRef } from "react";
import {
  ShieldCheck,
  RefreshCw,
  AlertCircle,
  Clock,
  ArrowRight,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { Link } from "@/i18n/routing";

// =============================================================================
// Types
// =============================================================================

interface Approval {
  run_id: string;
  project_id: string;
  agent_id: string;
  created_at: string;
  timeout_at: string | null;
}

// =============================================================================
// 常數
// =============================================================================

const API_BASE = process.env.NEXT_PUBLIC_API_URL ?? "";
const AUTO_REFRESH_INTERVAL = 10_000; // 10 秒

// =============================================================================
// Helpers
// =============================================================================

function getRemainingMs(timeoutAt: string | null): number | null {
  if (!timeoutAt) return null;
  return new Date(timeoutAt).getTime() - Date.now();
}

function formatRemaining(ms: number): string {
  if (ms <= 0) return "已超時";
  const totalSec = Math.floor(ms / 1000);
  const minutes = Math.floor(totalSec / 60);
  const seconds = totalSec % 60;
  if (minutes > 60) {
    const hours = Math.floor(minutes / 60);
    return `${hours}h ${minutes % 60}m`;
  }
  if (minutes > 0) return `${minutes}m ${seconds}s`;
  return `${seconds}s`;
}

// =============================================================================
// Sub Components
// =============================================================================

function TimeoutCell({ timeoutAt }: { timeoutAt: string | null }) {
  const [remaining, setRemaining] = useState<number | null>(
    getRemainingMs(timeoutAt)
  );

  useEffect(() => {
    if (!timeoutAt) return;
    const timer = setInterval(() => {
      setRemaining(getRemainingMs(timeoutAt));
    }, 1000);
    return () => clearInterval(timer);
  }, [timeoutAt]);

  if (remaining === null) return <span className="text-muted-foreground text-sm">--</span>;

  const isCritical = remaining <= 5 * 60 * 1000; // 5 分鐘內
  const isExpired = remaining <= 0;

  return (
    <span
      className={cn(
        "inline-flex items-center gap-1.5 font-mono text-sm",
        isExpired
          ? "text-red-400"
          : isCritical
          ? "text-red-300 font-semibold animate-pulse"
          : "text-muted-foreground"
      )}
      aria-label={`剩餘時間: ${formatRemaining(remaining)}`}
    >
      <Clock className="w-3.5 h-3.5" aria-hidden="true" />
      {formatRemaining(remaining)}
    </span>
  );
}

function ApprovalRow({ approval }: { approval: Approval }) {
  const formattedDate = approval.created_at
    ? new Date(approval.created_at).toLocaleDateString("zh-TW", {
        month: "2-digit",
        day: "2-digit",
        hour: "2-digit",
        minute: "2-digit",
      })
    : "--";

  const remainingMs = getRemainingMs(approval.timeout_at);
  const isCritical = remainingMs !== null && remainingMs <= 5 * 60 * 1000;

  return (
    <tr
      className={cn(
        "border-b border-border hover:bg-accent/30 transition-colors",
        isCritical && "bg-[#fff0ef] hover:bg-[#ffe4e1]"
      )}
    >
      <td className="px-4 py-3">
        <Link
          href={`/awooop/approvals/${approval.run_id}`}
          className="inline-flex items-center gap-1.5 font-mono text-xs text-brand-accent bg-brand-accent/10 px-2 py-1 rounded border border-brand-accent/20 hover:bg-brand-accent/20 transition-colors group"
          aria-label={`開啟審批 ${approval.run_id}`}
        >
          {approval.run_id.slice(0, 8)}
          <ArrowRight className="w-3 h-3 opacity-0 group-hover:opacity-100 transition-opacity" aria-hidden="true" />
        </Link>
      </td>
      <td className="px-4 py-3">
        <span className="font-mono text-sm text-muted-foreground">
          {approval.project_id || "--"}
        </span>
      </td>
      <td className="px-4 py-3">
        <span className="font-mono text-sm text-muted-foreground">
          {approval.agent_id || "--"}
        </span>
      </td>
      <td className="px-4 py-3">
        <span className="text-sm text-muted-foreground font-mono">
          {formattedDate}
        </span>
      </td>
      <td className="px-4 py-3">
        <TimeoutCell timeoutAt={approval.timeout_at} />
      </td>
    </tr>
  );
}

// =============================================================================
// Main Component
// =============================================================================

export default function ApprovalsPage() {
  const [approvals, setApprovals] = useState<Approval[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [lastRefresh, setLastRefresh] = useState<Date>(new Date());
  const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);

  const fetchApprovals = useCallback(async () => {
    try {
      setError(null);
      const res = await fetch(`${API_BASE}/api/v1/platform/approvals`);
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      const data = await res.json();
      setApprovals(Array.isArray(data.items) ? data.items : []);
      setLastRefresh(new Date());
    } catch (err) {
      setError(err instanceof Error ? err.message : "載入失敗");
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchApprovals();
  }, [fetchApprovals]);

  // 10 秒自動刷新
  useEffect(() => {
    intervalRef.current = setInterval(() => {
      fetchApprovals();
    }, AUTO_REFRESH_INTERVAL);
    return () => {
      if (intervalRef.current) clearInterval(intervalRef.current);
    };
  }, [fetchApprovals]);

  const criticalCount = approvals.filter((a) => {
    const ms = getRemainingMs(a.timeout_at);
    return ms !== null && ms <= 5 * 60 * 1000;
  }).length;

  return (
    <div className="space-y-6">
      {/* Page Header */}
      <div className="flex items-center justify-between flex-wrap gap-3">
        <div className="flex items-center gap-3">
          <ShieldCheck className="w-5 h-5 text-brand-accent" aria-hidden="true" />
          <div>
            <h2 className="text-lg font-semibold text-foreground flex items-center gap-2">
              審批佇列
              {criticalCount > 0 && (
                <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-bold bg-red-600 text-white animate-pulse">
                  {criticalCount} 緊急
                </span>
              )}
            </h2>
            <p className="text-xs text-muted-foreground">
              {loading
                ? "載入中..."
                : `${approvals.length} 筆待審 · 上次更新 ${lastRefresh.toLocaleTimeString("zh-TW")}`}
            </p>
          </div>
        </div>
        <div className="flex items-center gap-2">
          <span className="text-xs text-muted-foreground">每 10 秒自動刷新</span>
          <button
            onClick={() => { setLoading(true); fetchApprovals(); }}
            disabled={loading}
            className="flex items-center gap-2 px-3 py-2 text-sm text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition disabled:opacity-50"
            aria-label="立即重新整理"
          >
            <RefreshCw className={cn("w-4 h-4", loading && "animate-spin")} aria-hidden="true" />
            立即刷新
          </button>
        </div>
      </div>

      {/* Error State */}
      {error && (
        <div className="flex items-start gap-3 border border-[#e2a29b] bg-[#fff0ef] p-4">
          <AlertCircle className="w-5 h-5 text-red-400 flex-shrink-0 mt-0.5" aria-hidden="true" />
          <div>
            <p className="text-sm font-medium text-red-300">無法載入審批資料</p>
            <p className="text-xs text-red-400 mt-1">{error}</p>
          </div>
        </div>
      )}

      {/* Empty State — 所有審批已處理 */}
      {!loading && approvals.length === 0 && !error && (
        <div className="flex flex-col items-center justify-center border border-[#e0ddd4] bg-white py-16">
          <ShieldCheck className="w-12 h-12 text-green-400 mb-3" aria-hidden="true" />
          <p className="text-sm font-medium text-foreground mb-1">審批佇列為空</p>
          <p className="text-xs text-muted-foreground">目前沒有待審批的 Run</p>
        </div>
      )}

      {/* Table */}
      {(loading || approvals.length > 0) && (
        <div className="overflow-hidden border border-[#e0ddd4] bg-white shadow-[0_1px_4px_rgba(0,0,0,0.05)]">
          <div className="overflow-x-auto">
            <table className="w-full" role="table" aria-label="審批佇列">
              <thead>
                <tr className="border-b border-border bg-muted/50">
                  <th className="text-left px-4 py-3 text-xs font-medium text-muted-foreground uppercase tracking-wider">
                    Run ID
                  </th>
                  <th className="text-left px-4 py-3 text-xs font-medium text-muted-foreground uppercase tracking-wider">
                    Project ID
                  </th>
                  <th className="text-left px-4 py-3 text-xs font-medium text-muted-foreground uppercase tracking-wider">
                    Agent
                  </th>
                  <th className="text-left px-4 py-3 text-xs font-medium text-muted-foreground uppercase tracking-wider">
                    建立時間
                  </th>
                  <th className="text-left px-4 py-3 text-xs font-medium text-muted-foreground uppercase tracking-wider">
                    剩餘時間
                  </th>
                </tr>
              </thead>
              <tbody>
                {loading ? (
                  Array.from({ length: 5 }).map((_, i) => (
                    <tr key={i} className="border-b border-border">
                      {Array.from({ length: 5 }).map((_, j) => (
                        <td key={j} className="px-4 py-3">
                          <div className="h-5 bg-muted animate-pulse rounded w-20" />
                        </td>
                      ))}
                    </tr>
                  ))
                ) : (
                  approvals.map((approval) => (
                    <ApprovalRow key={approval.run_id} approval={approval} />
                  ))
                )}
              </tbody>
            </table>
          </div>
        </div>
      )}
    </div>
  );
}
