import { Button, Text, View } from "@tarojs/components";
import { useDidShow } from "@tarojs/taro";
import { useState } from "react";
import {
  approveAgentAction,
  bootstrapOfficialSession,
  executeAgentAction,
  getAgentActionDetail,
  listAgentPendingSummary,
  rejectAgentAction
} from "../../api/agent";
import { useAuthGuard } from "../../hooks/useAuthGuard";
import { useMemberGuard } from "../../hooks/useMemberGuard";
import "./index.scss";

function actionId(item: any) {
  return Number(item?.id || item?.actionRequestId || item?.action_request_id || 0);
}

function actionLabel(item: any) {
  return String(item?.display_name || item?.displayName || item?.action_code || item?.actionCode || "待确认动作");
}

function riskText(value: any) {
  const raw = String(value || "");
  const map: Record<string, string> = { L1: "只读", L2: "草稿", L3: "需确认", L4: "高风险" };
  return map[raw] || raw || "-";
}

function statusText(value: any) {
  const raw = String(value || "");
  const map: Record<string, string> = {
    pending_approval: "待批准",
    approved: "已批准",
    rejected: "已拒绝",
    executed: "已执行",
    failed: "执行失败"
  };
  return map[raw] || raw || "-";
}

function detailText(detail: any) {
  if (!detail) return "";
  const payload = detail.request_payload_json || detail.payload_json || detail.payload || detail.toolInput || {};
  return JSON.stringify(payload, null, 2);
}

export default function AiApprovalsPage() {
  useAuthGuard();
  useMemberGuard("连小新确认页仅面向正式会员开放");

  const [items, setItems] = useState<any[]>([]);
  const [details, setDetails] = useState<Record<number, any>>({});
  const [loading, setLoading] = useState(false);
  const [busyId, setBusyId] = useState(0);
  const [error, setError] = useState("");

  const load = async () => {
    setLoading(true);
    try {
      await bootstrapOfficialSession();
      const rows = await listAgentPendingSummary();
      setItems(Array.isArray(rows) ? rows : []);
      setError("");
    } catch (e: any) {
      setError(e?.message || "待确认动作加载失败");
    } finally {
      setLoading(false);
    }
  };

  useDidShow(() => {
    void load();
  });

  const toggleDetail = async (id: number) => {
    if (!id) return;
    if (details[id]) {
      setDetails((state) => {
        const next = { ...state };
        delete next[id];
        return next;
      });
      return;
    }
    try {
      const detail = await getAgentActionDetail(id);
      setDetails((state) => ({ ...state, [id]: detail }));
    } catch (e: any) {
      setError(e?.message || "详情加载失败");
    }
  };

  const approve = async (id: number) => {
    if (!id || busyId) return;
    setBusyId(id);
    try {
      const result = await approveAgentAction(id, "小程序待确认页批准");
      if (result?.executionToken) {
        await executeAgentAction(id, result.executionToken);
      }
      await load();
    } catch (e: any) {
      setError(e?.message || "批准失败");
    } finally {
      setBusyId(0);
    }
  };

  const reject = async (id: number) => {
    if (!id || busyId) return;
    setBusyId(id);
    try {
      await rejectAgentAction(id, "小程序待确认页拒绝");
      await load();
    } catch (e: any) {
      setError(e?.message || "拒绝失败");
    } finally {
      setBusyId(0);
    }
  };

  return (
    <View className="ai-page">
      <View className="ai-page__body">
        {error ? <Text className="ai-state is-error">{error}</Text> : null}
        {loading ? <Text className="ai-state">加载中...</Text> : null}
        <View className="ai-summary">
          <Text className="ai-summary__label">当前待确认</Text>
          <Text className="ai-summary__value">{items.length}</Text>
          <Button className="ai-summary__button" loading={loading} onClick={() => void load()}>刷新</Button>
        </View>
        {items.length === 0 && !loading ? <Text className="ai-state">当前没有待确认动作</Text> : null}
        {items.map((item) => {
          const id = actionId(item);
          const detail = details[id];
          return (
            <View key={id || actionLabel(item)} className="ai-card">
              <View className="ai-card__top">
                <Text className="ai-card__title">{actionLabel(item)}</Text>
                <Text className="ai-card__status">{statusText(item.status)}</Text>
              </View>
              <Text className="ai-card__meta">风险：{riskText(item.risk_level || item.riskLevel)} · 目标：{item.target_type || item.targetType || "-"}</Text>
              {item.reason ? <Text className="ai-card__reason">{item.reason}</Text> : null}
              {detail ? <Text className="ai-card__detail">{detailText(detail)}</Text> : null}
              <View className="ai-card__actions">
                <Text className="ai-card__link" onClick={() => void toggleDetail(id)}>{detail ? "收起详情" : "查看详情"}</Text>
                <Button className="ai-card__btn ai-card__btn--ghost" loading={busyId === id} onClick={() => void reject(id)}>拒绝</Button>
                <Button className="ai-card__btn" loading={busyId === id} onClick={() => void approve(id)}>批准执行</Button>
              </View>
            </View>
          );
        })}
      </View>
    </View>
  );
}
