// =============================================================================
// WOOO AIOps - AwoooP M8 審批決策頁面
// =============================================================================
// 顯示 Run 詳情，Approve / Reject 各需 Dialog 確認
// Reject 需填寫原因

"use client";

import { useState, useEffect, useCallback } from "react";
import { useRouter, Link } from "@/i18n/routing";
import {
  ShieldCheck,
  AlertCircle,
  CheckCircle,
  XCircle,
  ArrowLeft,
  RefreshCw,
  X,
} from "lucide-react";
import { cn } from "@/lib/utils";

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

interface RunDetail {
  run_id: string;
  project_id: string;
  agent_id: string;
  state: string;
  created_at: string;
  timeout_at?: string | null;
}

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

const API_BASE = process.env.NEXT_PUBLIC_API_URL ?? "";

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

function DetailRow({
  label,
  value,
}: {
  label: string;
  value: string | React.ReactNode;
}) {
  return (
    <div className="flex items-start py-3 border-b border-border last:border-0">
      <span className="w-32 flex-shrink-0 text-xs font-medium text-muted-foreground uppercase tracking-wider pt-0.5">
        {label}
      </span>
      <span className="text-sm text-foreground font-mono flex-1">{value}</span>
    </div>
  );
}

// Approve 確認 Dialog
function ApproveDialog({
  runId,
  onConfirm,
  onCancel,
  loading,
}: {
  runId: string;
  onConfirm: () => void;
  onCancel: () => void;
  loading: boolean;
}) {
  return (
    <div
      className="fixed inset-0 bg-black/60 backdrop-blur-sm flex items-center justify-center z-50 p-4"
      role="dialog"
      aria-modal="true"
      aria-labelledby="approve-dialog-title"
    >
      <div className="bg-card border border-border rounded-xl shadow-2xl w-full max-w-md">
        {/* Header */}
        <div className="flex items-center justify-between p-5 border-b border-border">
          <div className="flex items-center gap-3">
            <div className="p-2 bg-green-900/40 rounded-lg">
              <CheckCircle className="w-5 h-5 text-green-400" aria-hidden="true" />
            </div>
            <h3 id="approve-dialog-title" className="text-base font-semibold text-foreground">
              確認核准
            </h3>
          </div>
          <button
            onClick={onCancel}
            className="p-1.5 hover:bg-accent rounded-lg transition"
            aria-label="關閉"
          >
            <X className="w-4 h-4 text-muted-foreground" aria-hidden="true" />
          </button>
        </div>

        {/* Body */}
        <div className="p-5">
          <p className="text-sm text-foreground mb-2">確定要核准此 Run？</p>
          <div className="bg-muted rounded-lg px-3 py-2">
            <span className="text-xs text-muted-foreground font-mono">
              Run ID:{" "}
              <span className="text-brand-accent">{runId.slice(0, 8)}</span>
            </span>
          </div>
          <p className="text-xs text-muted-foreground mt-3">
            核准後，Run 將繼續執行後續步驟。此操作無法撤銷。
          </p>
        </div>

        {/* Footer */}
        <div className="flex items-center justify-end gap-3 p-5 border-t border-border bg-muted/30 rounded-b-xl">
          <button
            onClick={onCancel}
            disabled={loading}
            className="px-4 py-2 text-sm text-muted-foreground hover:bg-accent rounded-lg transition disabled:opacity-50"
          >
            取消
          </button>
          <button
            onClick={onConfirm}
            disabled={loading}
            className="flex items-center gap-2 px-4 py-2 text-sm font-medium bg-green-600 text-white rounded-lg hover:bg-green-700 transition disabled:opacity-50"
          >
            {loading && <RefreshCw className="w-3.5 h-3.5 animate-spin" aria-hidden="true" />}
            <CheckCircle className="w-3.5 h-3.5" aria-hidden="true" />
            確認核准
          </button>
        </div>
      </div>
    </div>
  );
}

// Reject 確認 Dialog（需填原因）
function RejectDialog({
  runId,
  onConfirm,
  onCancel,
  loading,
}: {
  runId: string;
  onConfirm: (reason: string) => void;
  onCancel: () => void;
  loading: boolean;
}) {
  const [reason, setReason] = useState("");

  return (
    <div
      className="fixed inset-0 bg-black/60 backdrop-blur-sm flex items-center justify-center z-50 p-4"
      role="dialog"
      aria-modal="true"
      aria-labelledby="reject-dialog-title"
    >
      <div className="bg-card border border-border rounded-xl shadow-2xl w-full max-w-md">
        {/* Header */}
        <div className="flex items-center justify-between p-5 border-b border-border">
          <div className="flex items-center gap-3">
            <div className="p-2 bg-red-900/40 rounded-lg">
              <XCircle className="w-5 h-5 text-red-400" aria-hidden="true" />
            </div>
            <h3 id="reject-dialog-title" className="text-base font-semibold text-foreground">
              確認拒絕
            </h3>
          </div>
          <button
            onClick={onCancel}
            className="p-1.5 hover:bg-accent rounded-lg transition"
            aria-label="關閉"
          >
            <X className="w-4 h-4 text-muted-foreground" aria-hidden="true" />
          </button>
        </div>

        {/* Body */}
        <div className="p-5 space-y-4">
          <div className="bg-muted rounded-lg px-3 py-2">
            <span className="text-xs text-muted-foreground font-mono">
              Run ID:{" "}
              <span className="text-red-400">{runId.slice(0, 8)}</span>
            </span>
          </div>

          <div>
            <label
              htmlFor="reject-reason"
              className="block text-sm font-medium text-foreground mb-2"
            >
              拒絕原因
              <span className="text-red-400 ml-1">*</span>
            </label>
            <textarea
              id="reject-reason"
              value={reason}
              onChange={(e) => setReason(e.target.value)}
              rows={3}
              placeholder="請輸入拒絕原因..."
              className="w-full px-3 py-2 text-sm bg-background border border-border rounded-lg text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-red-500/50 resize-none"
            />
          </div>

          <p className="text-xs text-muted-foreground">
            拒絕後，Run 將被終止。此操作無法撤銷。
          </p>
        </div>

        {/* Footer */}
        <div className="flex items-center justify-end gap-3 p-5 border-t border-border bg-muted/30 rounded-b-xl">
          <button
            onClick={onCancel}
            disabled={loading}
            className="px-4 py-2 text-sm text-muted-foreground hover:bg-accent rounded-lg transition disabled:opacity-50"
          >
            取消
          </button>
          <button
            onClick={() => onConfirm(reason.trim())}
            disabled={loading || reason.trim().length === 0}
            className="flex items-center gap-2 px-4 py-2 text-sm font-medium bg-red-600 text-white rounded-lg hover:bg-red-700 transition disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {loading && <RefreshCw className="w-3.5 h-3.5 animate-spin" aria-hidden="true" />}
            <XCircle className="w-3.5 h-3.5" aria-hidden="true" />
            確認拒絕
          </button>
        </div>
      </div>
    </div>
  );
}

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

export default function ApprovalDecisionPage({
  params,
}: {
  params: { run_id: string };
}) {
  const { run_id } = params;
  const router = useRouter();

  const [run, setRun] = useState<RunDetail | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [actionLoading, setActionLoading] = useState(false);
  const [actionError, setActionError] = useState<string | null>(null);
  const [actionSuccess, setActionSuccess] = useState<string | null>(null);
  const [showApproveDialog, setShowApproveDialog] = useState(false);
  const [showRejectDialog, setShowRejectDialog] = useState(false);

  const fetchRun = useCallback(async () => {
    try {
      setError(null);
      // 使用 approvals API 取得單筆 run 資訊
      const res = await fetch(`${API_BASE}/api/v1/platform/approvals?run_id=${run_id}`);
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      const data = await res.json();
      const item = Array.isArray(data.items)
        ? data.items.find((r: RunDetail) => r.run_id === run_id)
        : null;
      if (item) {
        setRun(item);
      } else {
        setRun({ run_id, project_id: "--", agent_id: "--", state: "--", created_at: "" });
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : "載入失敗");
    } finally {
      setLoading(false);
    }
  }, [run_id]);

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

  const handleApprove = async () => {
    setActionLoading(true);
    setActionError(null);
    try {
      const res = await fetch(
        `${API_BASE}/api/v1/platform/approvals/${run_id}/decide`,
        {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            decision: "approve",
            approver_id: "operator",
            reason: null,
          }),
        }
      );
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      setActionSuccess("Run 已成功核准");
      setShowApproveDialog(false);
      setTimeout(() => router.push("/awooop/approvals"), 1500);
    } catch (err) {
      setActionError(err instanceof Error ? err.message : "操作失敗");
      setShowApproveDialog(false);
    } finally {
      setActionLoading(false);
    }
  };

  const handleReject = async (reason: string) => {
    setActionLoading(true);
    setActionError(null);
    try {
      const res = await fetch(
        `${API_BASE}/api/v1/platform/approvals/${run_id}/decide`,
        {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            decision: "reject",
            approver_id: "operator",
            reason,
          }),
        }
      );
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      setActionSuccess("Run 已拒絕");
      setShowRejectDialog(false);
      setTimeout(() => router.push("/awooop/approvals"), 1500);
    } catch (err) {
      setActionError(err instanceof Error ? err.message : "操作失敗");
      setShowRejectDialog(false);
    } finally {
      setActionLoading(false);
    }
  };

  return (
    <>
      {/* Dialogs */}
      {showApproveDialog && (
        <ApproveDialog
          runId={run_id}
          onConfirm={handleApprove}
          onCancel={() => setShowApproveDialog(false)}
          loading={actionLoading}
        />
      )}
      {showRejectDialog && (
        <RejectDialog
          runId={run_id}
          onConfirm={handleReject}
          onCancel={() => setShowRejectDialog(false)}
          loading={actionLoading}
        />
      )}

      <div className="space-y-6 max-w-2xl">
        {/* Back Link */}
        <Link
          href="/awooop/approvals"
          className="inline-flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground transition-colors"
        >
          <ArrowLeft className="w-4 h-4" aria-hidden="true" />
          返回審批佇列
        </Link>

        {/* Page Header */}
        <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">審批決策</h2>
            <p className="text-xs text-muted-foreground font-mono">
              {run_id.slice(0, 8)}...
            </p>
          </div>
        </div>

        {/* Error / Success States */}
        {error && (
          <div className="flex items-start gap-3 p-4 bg-red-900/20 border border-red-800/40 rounded-lg">
            <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">無法載入 Run 資料</p>
              <p className="text-xs text-red-400 mt-1">{error}</p>
            </div>
          </div>
        )}

        {actionError && (
          <div className="flex items-start gap-3 p-4 bg-red-900/20 border border-red-800/40 rounded-lg">
            <AlertCircle className="w-5 h-5 text-red-400 flex-shrink-0 mt-0.5" aria-hidden="true" />
            <p className="text-sm text-red-300">{actionError}</p>
          </div>
        )}

        {actionSuccess && (
          <div className="flex items-center gap-3 p-4 bg-green-900/20 border border-green-800/40 rounded-lg">
            <CheckCircle className="w-5 h-5 text-green-400 flex-shrink-0" aria-hidden="true" />
            <p className="text-sm font-medium text-green-300">{actionSuccess}</p>
          </div>
        )}

        {/* Run Detail Card */}
        <div className="bg-card border border-border rounded-xl overflow-hidden shadow-sm">
          <div className="flex items-center justify-between px-5 py-4 border-b border-border bg-muted/30">
            <span className="text-sm font-medium text-foreground">Run 詳情</span>
            {loading && (
              <RefreshCw className="w-4 h-4 animate-spin text-muted-foreground" aria-hidden="true" />
            )}
          </div>

          <div className="px-5">
            {loading ? (
              Array.from({ length: 5 }).map((_, i) => (
                <div
                  key={i}
                  className="flex items-center py-3 border-b border-border last:border-0"
                >
                  <div className="w-32 h-4 bg-muted animate-pulse rounded mr-4" />
                  <div className="h-4 bg-muted animate-pulse rounded w-48" />
                </div>
              ))
            ) : run ? (
              <>
                <DetailRow label="Run ID" value={run.run_id} />
                <DetailRow label="Project ID" value={run.project_id || "--"} />
                <DetailRow label="Agent" value={run.agent_id || "--"} />
                <DetailRow
                  label="狀態"
                  value={
                    <span className="inline-flex items-center px-2.5 py-0.5 rounded-md text-xs font-medium bg-yellow-900/40 text-yellow-300 border border-yellow-600/40">
                      {run.state || "--"}
                    </span>
                  }
                />
                <DetailRow
                  label="建立時間"
                  value={
                    run.created_at
                      ? new Date(run.created_at).toLocaleString("zh-TW")
                      : "--"
                  }
                />
                {run.timeout_at && (
                  <DetailRow
                    label="超時時間"
                    value={new Date(run.timeout_at).toLocaleString("zh-TW")}
                  />
                )}
              </>
            ) : null}
          </div>
        </div>

        {/* Action Buttons */}
        {!loading && run && !actionSuccess && (
          <div className="flex items-center gap-3">
            <button
              onClick={() => setShowApproveDialog(true)}
              disabled={actionLoading}
              className={cn(
                "flex-1 flex items-center justify-center gap-2 py-3 px-6",
                "text-sm font-semibold rounded-xl border transition-all duration-150",
                "bg-green-900/30 text-green-300 border-green-600/40",
                "hover:bg-green-900/60 hover:border-green-500/60",
                "disabled:opacity-50 disabled:cursor-not-allowed",
                "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-green-500/50"
              )}
            >
              <CheckCircle className="w-4 h-4" aria-hidden="true" />
              核准
            </button>
            <button
              onClick={() => setShowRejectDialog(true)}
              disabled={actionLoading}
              className={cn(
                "flex-1 flex items-center justify-center gap-2 py-3 px-6",
                "text-sm font-semibold rounded-xl border transition-all duration-150",
                "bg-red-900/30 text-red-300 border-red-600/40",
                "hover:bg-red-900/60 hover:border-red-500/60",
                "disabled:opacity-50 disabled:cursor-not-allowed",
                "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-red-500/50"
              )}
            >
              <XCircle className="w-4 h-4" aria-hidden="true" />
              拒絕
            </button>
          </div>
        )}
      </div>
    </>
  );
}
