import { Text, View } from "@tarojs/components";
import type { PendingAction } from "../types";
import type { AgentCatalogAction } from "../../../api/agent";
import { UI_TEXT } from "../constants";
import "./action_card.scss";

interface ActionCardProps {
  pending: PendingAction;
  capability?: AgentCatalogAction;
  onConfirm: () => void;
  onCancel: () => void;
}

export function ActionCard({ pending, capability, onConfirm, onCancel }: ActionCardProps) {
  const label = capability?.displayName || UI_TEXT.actionNames[pending.actionCode] || pending.actionCode;
  const riskLevel = getRiskLevel(pending.actionCode, capability);
  const riskLabel = UI_TEXT.riskLevels[riskLevel] || riskLevel;
  const riskClass = "is-" + riskLevel;
  const blocked = capability?.allowedByRole === false || capability?.availableByRole === false;
  const requiredFields = Array.isArray(capability?.requiredFields) ? capability.requiredFields : [];
  const description = capability?.description || UI_TEXT.actionDescriptions[pending.actionCode] || "即将执行此操作";

  return (
    <View className={"action-card " + (blocked ? "is-blocked" : "")}>
      <View className="action-card__header">
        <Text className="action-card__eyebrow">待确认事项</Text>
        <Text className="action-card__title">{label}</Text>
        <View className={"action-card__risk " + riskClass}>
          <Text>{riskLabel}</Text>
        </View>
      </View>
      <View className="action-card__body">
        <Text className="action-card__desc">
          {description}
        </Text>
        {capability ? (
          <View className="action-card__meta">
            <Text>{capability.module || capability.moduleCode || "工具"}</Text>
            <Text>{capability.executionMode === "runtime" ? "Agent Runtime" : "Gateway"}</Text>
            {requiredFields.length ? <Text>必填 {requiredFields.join(" / ")}</Text> : null}
          </View>
        ) : null}
        {pending.reason && (
          <Text className="action-card__reason">原因：{pending.reason}</Text>
        )}
        {blocked ? <Text className="action-card__warning">当前账号或授权范围暂不能执行这个工具。</Text> : null}
      </View>
      <View className="action-card__actions">
        <View className="action-card__btn is-cancel" onClick={onCancel}>
          <Text>取消</Text>
        </View>
        <View className={"action-card__btn is-confirm " + (blocked ? "is-disabled" : "")} onClick={() => {
          if (!blocked) onConfirm();
        }}>
          <Text>确认提交</Text>
        </View>
      </View>
    </View>
  );
}

function getRiskLevel(code: string, capability?: AgentCatalogAction): "low" | "medium" | "high" {
  const risk = String(capability?.riskLevel || "").toUpperCase();
  if (risk === "L1") return "low";
  if (risk === "L4") return "high";
  if (risk === "L2" || risk === "L3") return "medium";
  if (code.includes("delete") || code.includes("disable")) return "high";
  if (code.includes("submit") || code.includes("create")) return "medium";
  return "low";
}
