"use client";

import { useCallback, useEffect, useState } from "react";
import { TopBar, type Mode } from "@/components/TopBar";
import { ACTIONS, DEBT_SPECIFIC_LEVERS } from "@/lib/actions";
import { CFO_ROLES, cfoRoleForKey, cfoRoleTitleForKey, type CfoRole } from "@/lib/cfoRoles";
import { formatVND, formatVNDCompact, periodKey } from "@/lib/finance";
import { evaluateEffectiveness } from "@/lib/performance";
import { ActualAmountConfirm } from "@/components/ActualAmountConfirm";
import { ForecastLineChart } from "@/components/ForecastLineChart";
import { AllocationDonut } from "@/components/AllocationDonut";
import { ICONS } from "@/lib/icons";
import { fetchRetry } from "@/lib/httpRetry";

const CYCLE_LABEL: Record<string, string> = { DAILY_OPEN: "Đầu ngày", DAILY_CLOSE: "Cuối ngày", WEEKLY: "Hàng tuần" };

function currentPeriod() {
  return periodKey(new Date());
}

const STATUS_LABEL: Record<string, string> = {
  PENDING: "Chờ duyệt",
  ASSIGNED: "Chờ duyệt",
  RUNNING: "Đang thực hiện",
  REVIEW: "Chờ duyệt",
  DONE: "Hoàn thành",
  FAILED: "Thất bại",
  BLOCKED: "Bị chặn",
  AWAITING_USER: "Chờ bạn thực hiện",
};
const STATUS_STYLE: Record<string, string> = {
  PENDING: "bg-amber-100 text-amber-700",
  ASSIGNED: "bg-amber-100 text-amber-700",
  RUNNING: "bg-indigo-100 text-indigo-700",
  REVIEW: "bg-amber-100 text-amber-700",
  DONE: "bg-emerald-100 text-emerald-700",
  FAILED: "bg-rose-100 text-rose-700",
  BLOCKED: "bg-rose-100 text-rose-700",
  AWAITING_USER: "bg-amber-100 text-amber-700",
};
// 3 nhóm lọc theo đúng mockup — FAILED/BLOCKED cố ý không rơi vào "Chờ duyệt" (sai bản chất), vẫn
// hiện đầy đủ trong "Tất cả" với badge đỏ riêng.
function statusBucket(status: string): "PENDING_APPROVAL" | "IN_PROGRESS" | "DONE" | "OTHER" {
  if (status === "DONE") return "DONE";
  if (status === "RUNNING") return "IN_PROGRESS";
  if (["PENDING", "ASSIGNED", "REVIEW", "AWAITING_USER"].includes(status)) return "PENDING_APPROVAL";
  return "OTHER";
}

const CASH_HEALTH_STYLE: Record<string, { label: string; className: string; icon: "verified" | "alert" }> = {
  SAFE: { label: "Dòng tiền đang an toàn", className: "bg-emerald-50 text-emerald-700 border-emerald-200", icon: "verified" },
  WARNING: { label: "Dòng tiền cần chú ý", className: "bg-amber-50 text-amber-700 border-amber-200", icon: "alert" },
  NEGATIVE: { label: "Dòng tiền có nguy cơ âm", className: "bg-rose-50 text-rose-700 border-rose-200", icon: "alert" },
  NO_DATA: { label: "Chưa đủ dữ liệu để đánh giá", className: "bg-slate-100 text-slate-600 border-slate-200", icon: "alert" },
};
const TARGET_STATUS_STYLE: Record<string, { label: string; className: string }> = {
  NO_TARGET: { label: "Chưa đặt mục tiêu", className: "bg-slate-100 text-slate-500" },
  ON_TRACK: { label: "Đạt mục tiêu", className: "bg-emerald-50 text-emerald-700" },
  AT_RISK: { label: "Chưa đạt — còn phương án", className: "bg-amber-50 text-amber-700" },
  INFEASIBLE: { label: "Không khả thi với cách làm hiện tại", className: "bg-rose-50 text-rose-700" },
};

export default function ActionsPage() {
  const [mode, setMode] = useState<Mode>("CONSOLIDATED");
  const [period, setPeriod] = useState(currentPeriod());
  const [items, setItems] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [launchKey, setLaunchKey] = useState<number>(1);
  const [launchScope, setLaunchScope] = useState("CONSOLIDATED");
  const [cfo, setCfo] = useState<any>(null);
  const [cfoLoading, setCfoLoading] = useState(true);
  const [dash, setDash] = useState<any>(null);
  const [roleFilter, setRoleFilter] = useState<CfoRole | null>(null);
  const [statusFilter, setStatusFilter] = useState<"ALL" | "PENDING_APPROVAL" | "IN_PROGRESS" | "DONE">("ALL");
  const [toast, setToast] = useState<string | null>(null);
  const [launching, setLaunching] = useState(false);
  const [answering, setAnswering] = useState<string | null>(null);
  const [answerValue, setAnswerValue] = useState("");
  const [answerValue2, setAnswerValue2] = useState("");
  const [conversation, setConversation] = useState<any[]>([]);
  const [question, setQuestion] = useState("");
  const [asking, setAsking] = useState(false);
  const [agentDefs, setAgentDefs] = useState<any[]>([]);
  const [agentResults, setAgentResults] = useState<Record<string, any>>({});
  const [agentLoadingId, setAgentLoadingId] = useState<string | null>(null);
  const [openAgentId, setOpenAgentId] = useState<string | null>(null);

  const load = useCallback(async () => {
    setLoading(true);
    const res = await fetch("/api/actions");
    const json = await res.json();
    setItems(json.items);
    setLoading(false);
  }, []);

  const loadCfo = useCallback(
    async (force = false) => {
      setCfoLoading(true);
      const res = await fetch(`/api/ai/cfo-summary?scope=${mode}&period=${period}${force ? "&force=1" : ""}`);
      const json = await res.json();
      setCfo(json);
      setCfoLoading(false);
    },
    [mode, period]
  );

  const loadDash = useCallback(async () => {
    const res = await fetch(`/api/dashboard?mode=${mode}&period=${period}`);
    setDash(await res.json());
  }, [mode, period]);

  const loadConversation = useCallback(async () => {
    const res = await fetch(`/api/ai/ask?scope=${mode}`);
    const json = await res.json();
    setConversation(json.history ?? []);
  }, [mode]);

  useEffect(() => {
    load();
  }, [load]);
  useEffect(() => {
    loadCfo();
    loadDash();
    loadConversation();
    setAgentResults({});
  }, [loadCfo, loadDash, loadConversation]);
  useEffect(() => {
    fetch("/api/ai/agents")
      .then((r) => r.json())
      .then((json) => setAgentDefs(json.agents ?? []));
  }, []);

  async function askCfo() {
    if (!question.trim()) return;
    setAsking(true);
    try {
      await fetch("/api/ai/ask", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ scope: mode, question: question.trim() }),
      });
      setQuestion("");
      await loadConversation();
    } finally {
      setAsking(false);
    }
  }

  async function runAgent(id: string) {
    setOpenAgentId(openAgentId === id ? null : id);
    if (agentResults[id]) return;
    setAgentLoadingId(id);
    try {
      const res = await fetch(`/api/ai/agents/${id}?scope=${mode}`);
      const json = await res.json();
      setAgentResults((prev) => ({ ...prev, [id]: json }));
    } finally {
      setAgentLoadingId(null);
    }
  }

  async function launch() {
    setLaunching(true);
    try {
      if (DEBT_SPECIFIC_LEVERS[launchKey]) {
        // Đòn bẩy gắn với từng khoản nợ thật (1 = thu hồi công nợ, 7 = đàm phán công nợ phải trả) ->
        // sinh MỖI khoản nợ mở một việc riêng (tên/số tiền thật), không gộp thành 1 dòng chung chung.
        const res = await fetch("/api/actions/generate", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ actionKey: launchKey, scope: launchScope }),
        });
        const json = await res.json();
        setToast(json.message);
      } else {
        // Gắn đúng expectedAmount/confidence rule-based đã tính cho đòn bẩy này (allScores từ
        // cfo-summary) thay vì tạo nhiệm vụ với tác động tài chính = 0.
        const scoresRes = await fetch(`/api/ai/cfo-summary?scope=${launchScope}&period=${period}`).then((r) => r.json());
        const sc = scoresRes.allScores?.find((s: any) => s.key === launchKey);
        const res = await fetch("/api/actions", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ actionKey: launchKey, scope: launchScope, expectedAmount: sc?.cashImpact, confidence: sc?.confidence }),
        });
        const json = await res.json();
        setToast(json.deduped ? "Đã có việc này đang mở — không tạo trùng." : "Đã tạo nhiệm vụ mới.");
      }
      load();
    } finally {
      setLaunching(false);
      setTimeout(() => setToast(null), 4000);
    }
  }

  // "AI CFO hỏi CEO khi thiếu dữ liệu quan trọng" — trả lời lưu THẬT vào Target/BalanceBaseline
  // qua đúng API đã có, không phải hội thoại/ghi nhớ giả.
  async function submitAnswer(questionId: string) {
    const scope = mode === "CONSOLIDATED" ? "CONSOLIDATED" : mode;
    if (questionId === "baseline") {
      if (!answerValue) return;
      await fetch("/api/balance", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ scope, asOfDate: new Date().toISOString(), amount: Number(answerValue) }),
      });
    } else if (questionId === "target") {
      if (!answerValue || !answerValue2) return;
      await fetch("/api/targets", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ scope, targetNetCashFlow: Number(answerValue), targetDays: Number(answerValue2) }),
      });
    } else if (questionId === "safety") {
      if (!answerValue) return;
      await fetch("/api/targets", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ scope, safetyBalance: Number(answerValue) }),
      });
    }
    setAnswering(null);
    setAnswerValue("");
    setAnswerValue2("");
    loadCfo(true);
  }

  async function assign(id: string) {
    const owner = prompt("Giao cho ai? (VD: Sales A, Kế toán B)");
    if (!owner) return;
    await fetchRetry(`/api/actions/${id}`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ status: "ASSIGNED", owner }),
    });
    load();
  }

  async function run(id: string) {
    await fetchRetry(`/api/actions/${id}/run`, { method: "POST" });
    load();
  }

  async function analyze(id: string) {
    const res = await fetch("/api/ai/analyze", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ actionItemId: id }),
    });
    const json = await res.json();
    alert(json.result.text);
    load();
  }

  const scopedItems = items.filter((i) => mode === "CONSOLIDATED" || i.scope === mode);
  const filteredItems = scopedItems
    .filter((i) => !roleFilter || cfoRoleForKey(i.actionKey) === roleFilter)
    .filter((i) => statusFilter === "ALL" || statusBucket(i.status) === statusFilter);
  const bucketCounts = {
    ALL: scopedItems.length,
    PENDING_APPROVAL: scopedItems.filter((i) => statusBucket(i.status) === "PENDING_APPROVAL").length,
    IN_PROGRESS: scopedItems.filter((i) => statusBucket(i.status) === "IN_PROGRESS").length,
    DONE: scopedItems.filter((i) => statusBucket(i.status) === "DONE").length,
  };
  const roleGoiYCount = (role: CfoRole) => (cfo?.allScores ?? []).filter((s: any) => cfoRoleForKey(s.key) === role && s.cashImpact > 0).length;

  const health = CASH_HEALTH_STYLE[cfo?.cashHealth ?? "NO_DATA"];
  const HealthIcon = ICONS[health.icon];

  // F — Kết quả & hiệu quả: tách "tiền thu thêm" (nhóm đòn bẩy tăng thu) và "tiền tiết kiệm" (nhóm
  // giảm chi/tối ưu) từ chính các ActionItem đã được NGƯỜI DÙNG tự xác nhận actualAmount — không suy đoán.
  const verified = scopedItems.filter((i) => i.status === "DONE" && i.actualAmount !== 0);
  const thuThem = verified.filter((i) => ACTIONS.find((a) => a.key === i.actionKey)?.group === "INCREASE_INFLOW").reduce((s, i) => s + i.actualAmount, 0);
  const tietKiem = verified.filter((i) => ACTIONS.find((a) => a.key === i.actionKey)?.group !== "INCREASE_INFLOW").reduce((s, i) => s + i.actualAmount, 0);
  const launchedCount = scopedItems.length;
  const doneCount = bucketCounts.DONE;
  // Agent Chiến lược & Hiệu quả — so kết quả thật với kỳ vọng ban đầu, phát hiện hành động kém hiệu
  // quả để đề xuất điều chỉnh (không tự xoá/tự dừng — chỉ gợi ý, người dùng tự quyết định).
  const underperforming = verified
    .map((i) => ({ item: i, verdict: evaluateEffectiveness(i.expectedAmount, i.actualAmount) }))
    .filter((x) => x.verdict.underperforming);

  return (
    <div>
      <TopBar
        mode={mode}
        onModeChange={setMode}
        period={period}
        onPeriodChange={setPeriod}
        title="Hành động & Agent"
        subtitle="AI tự động phân tích dữ liệu, đề xuất và điều phối hành động để đảm bảo dòng tiền luôn dương."
      />

      <div className="flex flex-col gap-6 p-8">
        {/* A. AI CFO — kết luận & hành động đề xuất hôm nay */}
        <div className="card grid grid-cols-1 gap-4 border-teal-100 bg-gradient-to-br from-teal-50/60 to-white p-5 lg:grid-cols-[2fr_1fr]">
          <div>
            <div className="mb-2 flex items-center justify-between">
              <div className="flex items-center gap-2">
                <span className="flex h-7 w-7 items-center justify-center rounded-lg bg-teal-500 text-white">
                  <ICONS.aiCfo size={16} strokeWidth={1.75} />
                </span>
                <span className="text-xs font-bold uppercase tracking-wide text-teal-700">AI CFO</span>
              </div>
              <button
                onClick={() => loadCfo(true)}
                disabled={cfoLoading}
                className="flex items-center gap-1.5 rounded-lg border border-teal-200 px-3 py-1.5 text-xs font-semibold text-teal-700 hover:bg-teal-50 disabled:opacity-50"
              >
                <ICONS.refresh size={13} strokeWidth={1.75} className={cfoLoading ? "animate-spin" : ""} /> Phân tích lại ngay
              </button>
            </div>
            <div className="mb-1 text-sm font-bold text-slate-800">Kết luận & hành động đề xuất hôm nay</div>
            {cfoLoading && !cfo ? (
              <div className="py-4 text-sm text-slate-400">Đang phân tích...</div>
            ) : (
              <>
                <div className="mb-3 flex flex-wrap items-center gap-2">
                  <div className={`inline-flex items-center gap-2 rounded-lg border px-3 py-2 text-sm font-semibold ${health.className}`}>
                    <HealthIcon size={16} strokeWidth={1.75} /> {health.label}
                  </div>
                  {cfo?.targetStatus && (
                    <div
                      className={`inline-flex items-center gap-1.5 rounded-lg px-3 py-2 text-xs font-semibold ${TARGET_STATUS_STYLE[cfo.targetStatus.status].className}`}
                      title={cfo.targetStatus.note}
                    >
                      <ICONS.target size={14} strokeWidth={1.75} /> Target: {TARGET_STATUS_STYLE[cfo.targetStatus.status].label}
                    </div>
                  )}
                  {cfo?.overdueActions > 0 && (
                    <div className="inline-flex items-center gap-1.5 rounded-lg bg-rose-50 px-3 py-2 text-xs font-semibold text-rose-700">
                      <ICONS.alert size={14} strokeWidth={1.75} /> {cfo.overdueActions} việc đang trễ hạn
                    </div>
                  )}
                </div>
                {cfo?.targetStatus?.status !== "NO_TARGET" && cfo?.targetStatus?.status !== "ON_TRACK" && (
                  <p className="mb-2 text-xs text-slate-500">{cfo.targetStatus.note}</p>
                )}
                <p className="mb-3 text-xs text-slate-500">{cfo?.reasoning}</p>
                <div className="grid grid-cols-2 gap-3 sm:grid-cols-3">
                  <div>
                    <div className="text-[11px] text-slate-400">Số dư hiện tại</div>
                    <div className="text-base font-bold text-slate-800">{formatVND(cfo?.balance ?? 0)}</div>
                  </div>
                  <div>
                    <div className="text-[11px] text-slate-400">Dự báo 30 ngày</div>
                    <div className="text-base font-bold text-slate-800">{formatVND(cfo?.forecast30 ?? 0)}</div>
                  </div>
                  <div>
                    <div className="text-[11px] text-slate-400">Ngày có nguy cơ thiếu</div>
                    <div className="text-base font-bold text-slate-800">{cfo?.shortfallDate ?? "—"}</div>
                  </div>
                  {cfo?.targetDaysLeft !== null && (
                    <div>
                      <div className="text-[11px] text-slate-400">Còn lại tới deadline target</div>
                      <div className="text-base font-bold text-slate-800">{cfo?.targetDaysLeft} ngày</div>
                    </div>
                  )}
                </div>
                <div className="mt-2 text-[10px] text-slate-400">
                  Nguồn: {cfo?.source === "claude" ? "Claude (phân tích AI thật)" : "Rule-based (Claude chưa cấu hình ANTHROPIC_API_KEY)"} · Độ tin cậy ước tính {Math.round((cfo?.confidence ?? 0) * 100)}%
                </div>
                <div className="mt-2 flex flex-wrap gap-x-4 gap-y-1 border-t border-teal-100/70 pt-2 text-[10px] text-slate-400">
                  {(["DAILY_OPEN", "DAILY_CLOSE", "WEEKLY"] as const).map((cycle) => {
                    const run = cfo?.schedulerRuns?.[cycle];
                    return (
                      <span key={cycle} title={run?.summary ?? undefined}>
                        {CYCLE_LABEL[cycle]}: {run ? new Date(run.createdAt).toLocaleString("vi-VN") : "chưa chạy lần nào"}
                      </span>
                    );
                  })}
                </div>
              </>
            )}
          </div>
          <div className="rounded-xl bg-white/70 p-4">
            <div className="mb-1 flex items-center gap-2 text-sm font-bold text-slate-800">
              <ICONS.suggestion size={16} strokeWidth={1.75} className="text-amber-500" /> Ưu tiên hôm nay
            </div>
            <p className="text-xs text-slate-500">{cfo?.priorityNote}</p>
            {cfo?.topActions?.length > 0 && (
              <ul className="mt-2 flex flex-col gap-1 text-xs text-slate-600">
                {cfo.topActions.map((a: any) => (
                  <li key={a.key} className="flex items-center justify-between">
                    <span>{a.title}</span>
                    <span className="font-semibold text-teal-600">{formatVNDCompact(a.cashImpact)}</span>
                  </li>
                ))}
              </ul>
            )}
            <a href="#priority-table" className="mt-2 inline-flex items-center gap-1 text-xs font-semibold text-teal-600 hover:underline">
              Xem chi tiết phân tích <ICONS.chevronRight size={13} strokeWidth={1.75} />
            </a>
          </div>
        </div>

        {/* AI CFO hỏi CEO khi thiếu dữ liệu quan trọng — trả lời lưu thật vào DB, không phải chat */}
        {cfo?.ceoQuestions?.length > 0 && (
          <div className="card flex flex-col gap-3 border-amber-200 bg-amber-50/60 p-5">
            <div className="flex items-center gap-2 font-bold text-amber-800">
              <ICONS.alert size={18} strokeWidth={1.75} /> AI CFO cần bạn trả lời ({cfo.ceoQuestions.length})
            </div>
            {cfo.ceoQuestions.map((q: any) => (
              <div key={q.id} className="flex flex-wrap items-center gap-2 rounded-lg bg-white p-3 text-sm">
                <span className="flex-1 font-medium text-slate-700">{q.question}</span>
                {answering === q.id ? (
                  <>
                    <input
                      value={answerValue}
                      onChange={(e) => setAnswerValue(e.target.value.replace(/[^\d]/g, ""))}
                      placeholder={q.action === "target" ? "Số tiền mục tiêu" : "Số tiền"}
                      className="w-32 rounded-lg border border-slate-200 px-2 py-1.5 text-xs"
                    />
                    {q.action === "target" && (
                      <input
                        value={answerValue2}
                        onChange={(e) => setAnswerValue2(e.target.value.replace(/[^\d]/g, ""))}
                        placeholder="Số ngày"
                        className="w-24 rounded-lg border border-slate-200 px-2 py-1.5 text-xs"
                      />
                    )}
                    <button onClick={() => submitAnswer(q.id)} className="rounded-lg bg-teal-500 px-3 py-1.5 text-xs font-semibold text-white">
                      Lưu
                    </button>
                    <button onClick={() => setAnswering(null)} className="text-xs text-slate-400 hover:underline">
                      Huỷ
                    </button>
                  </>
                ) : (
                  <button
                    onClick={() => {
                      setAnswering(q.id);
                      setAnswerValue("");
                      setAnswerValue2("");
                    }}
                    className="rounded-lg border border-amber-300 px-3 py-1.5 text-xs font-semibold text-amber-700 hover:bg-amber-50"
                  >
                    Trả lời
                  </button>
                )}
              </div>
            ))}
          </div>
        )}

        {/* Hỏi AI CFO — hội thoại TỰ DO, không giới hạn danh sách cố định. Claude thật khi có
            ANTHROPIC_API_KEY, rule-based đối chiếu số liệu thật khi chưa có (luôn ghi rõ nguồn). */}
        <div className="card flex flex-col gap-3 p-5">
          <div className="flex items-center gap-2 font-bold text-slate-800">
            <ICONS.suggestion size={18} strokeWidth={1.75} className="text-teal-500" /> Hỏi AI CFO
          </div>
          <p className="text-xs text-slate-400">Gõ bất kỳ câu hỏi nào về dòng tiền, công nợ, mục tiêu, deadline — không giới hạn câu có sẵn. Lịch sử được lưu lại.</p>
          <div className="flex gap-2">
            <input
              value={question}
              onChange={(e) => setQuestion(e.target.value)}
              onKeyDown={(e) => e.key === "Enter" && askCfo()}
              placeholder="VD: Tháng này còn thiếu bao nhiêu để đạt mục tiêu?"
              className="flex-1 rounded-lg border border-slate-200 px-3 py-2 text-sm"
            />
            <button onClick={askCfo} disabled={asking || !question.trim()} className="rounded-lg bg-teal-500 px-4 py-2 text-sm font-semibold text-white disabled:opacity-50">
              {asking ? "Đang hỏi..." : "Hỏi"}
            </button>
          </div>
          {conversation.length > 0 && (
            <div className="flex flex-col gap-3 border-t border-slate-100 pt-3">
              {conversation.map((c) => (
                <div key={c.id} className="text-sm">
                  <div className="font-medium text-slate-700">Bạn: {c.question}</div>
                  <div className="mt-0.5 text-slate-500">
                    AI CFO: {c.answer}{" "}
                    <span className="text-[10px] text-slate-300">({c.source === "claude" ? "Claude" : "rule-based"})</span>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* 4 Agent chuyên môn */}
        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
          {CFO_ROLES.map((role) => {
            const Icon = ICONS[role.icon];
            const count = roleGoiYCount(role.key);
            const active = roleFilter === role.key;
            return (
              <div key={role.key} className={`card flex flex-col gap-2 p-4 ${active ? "border-teal-300 ring-1 ring-teal-200" : ""}`}>
                <span className={`flex h-10 w-10 items-center justify-center rounded-xl ${role.badgeClassName}`}>
                  <Icon size={19} strokeWidth={1.75} />
                </span>
                <div className="text-sm font-bold text-slate-800">{role.title}</div>
                <p className="text-xs text-slate-400">{role.description}</p>
                <div className="mt-auto flex items-center justify-between pt-1">
                  <span className={`rounded-full px-2 py-0.5 text-[11px] font-semibold ${role.badgeClassName}`}>{count} gợi ý</span>
                  <button
                    onClick={() => setRoleFilter(active ? null : role.key)}
                    className="flex items-center gap-1 text-xs font-semibold text-teal-600 hover:underline"
                  >
                    {active ? "Bỏ lọc" : "Xem gợi ý"} <ICONS.chevronRight size={14} strokeWidth={1.75} />
                  </button>
                </div>
              </div>
            );
          })}
        </div>
        {/* 10 Agent độc lập thật (mỗi cái Input→Process→Output→KPI riêng, xem lib/agents.ts) —
            CỘNG với AI CFO ở banner đầu trang = đủ 11 vai trò. Chạy theo yêu cầu (bấm mới gọi),
            không tự động chạy hàng loạt mỗi lần tải trang. */}
        <div className="card overflow-hidden">
          <div className="border-b border-slate-100 p-4">
            <div className="font-bold text-slate-800">10 Agent độc lập (+ AI CFO ở trên)</div>
            <p className="text-xs text-slate-400">Mỗi Agent có Input → Process → Output → KPI → điều kiện hoàn thành riêng, tái sử dụng đúng engine tài chính đã có. Bấm "Chạy" để xem kết quả thật ngay.</p>
          </div>
          <div className="divide-y divide-slate-50">
            {agentDefs.map((a) => {
              const result = agentResults[a.id];
              const isOpen = openAgentId === a.id;
              return (
                <div key={a.id} className="p-4">
                  <div className="flex flex-wrap items-center justify-between gap-2">
                    <div>
                      <div className="text-sm font-semibold text-slate-700">{a.title}</div>
                      <div className="text-xs text-slate-400">{a.skill}</div>
                    </div>
                    <button
                      onClick={() => runAgent(a.id)}
                      disabled={agentLoadingId === a.id}
                      className="shrink-0 rounded-lg border border-teal-200 px-3 py-1.5 text-xs font-semibold text-teal-700 hover:bg-teal-50 disabled:opacity-50"
                    >
                      {agentLoadingId === a.id ? "Đang chạy..." : isOpen ? "Thu gọn" : result ? "Xem kết quả" : "Chạy"}
                    </button>
                  </div>
                  {isOpen && result && (
                    <div className="mt-3 grid grid-cols-1 gap-3 rounded-lg bg-slate-50 p-3 text-xs sm:grid-cols-3">
                      <div>
                        <div className="mb-1 font-semibold uppercase text-slate-400">Input</div>
                        <pre className="whitespace-pre-wrap break-words text-slate-600">{JSON.stringify(result.input, null, 1)}</pre>
                      </div>
                      <div>
                        <div className="mb-1 font-semibold uppercase text-slate-400">Output</div>
                        <pre className="whitespace-pre-wrap break-words text-slate-600">{JSON.stringify(result.output, null, 1)}</pre>
                      </div>
                      <div>
                        <div className="mb-1 font-semibold uppercase text-slate-400">KPI</div>
                        <pre className="whitespace-pre-wrap break-words text-slate-600">{JSON.stringify(result.kpi, null, 1)}</pre>
                        <div className="mt-2 text-[11px] italic text-slate-400">{result.completionCondition}</div>
                      </div>
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        </div>

        {/* C. Bảng hành động ưu tiên */}
        <div id="priority-table" className="card scroll-mt-6 overflow-hidden">
          <div className="flex flex-wrap items-center justify-between gap-3 border-b border-slate-100 p-5">
            <div>
              <div className="flex items-center gap-2 font-bold text-slate-800">
                <span className="flex h-6 w-6 items-center justify-center rounded-full bg-teal-500 text-xs font-bold text-white">{bucketCounts.ALL}</span>
                Hành động ưu tiên (1–3 việc để đảm bảo dòng tiền dương)
              </div>
              <p className="text-xs text-slate-400">Được AI phân tích từ dữ liệu thực tế của bạn. Ưu tiên theo tác động tài chính, khả năng thực hiện và rủi ro.</p>
            </div>
            <div className="flex overflow-hidden rounded-lg border border-slate-200 text-xs">
              {(
                [
                  ["ALL", `Tất cả (${bucketCounts.ALL})`],
                  ["PENDING_APPROVAL", `Chờ duyệt (${bucketCounts.PENDING_APPROVAL})`],
                  ["IN_PROGRESS", `Đang thực hiện (${bucketCounts.IN_PROGRESS})`],
                  ["DONE", `Hoàn thành (${bucketCounts.DONE})`],
                ] as const
              ).map(([key, label]) => (
                <button
                  key={key}
                  onClick={() => setStatusFilter(key)}
                  className={`px-3 py-1.5 font-medium ${statusFilter === key ? "bg-teal-500 text-white" : "bg-white text-slate-500 hover:bg-slate-50"}`}
                >
                  {label}
                </button>
              ))}
            </div>
          </div>

          <div className="flex flex-wrap items-end gap-3 border-b border-slate-100 bg-slate-50/60 p-4">
            <label className="text-xs text-slate-500">
              Hành động
              <select value={launchKey} onChange={(e) => setLaunchKey(Number(e.target.value))} className="mt-1 block rounded-lg border border-slate-200 px-3 py-2 text-sm">
                {ACTIONS.map((a) => (
                  <option key={a.key} value={a.key}>
                    {a.key}. {a.title}
                  </option>
                ))}
              </select>
            </label>
            <label className="text-xs text-slate-500">
              Phạm vi
              <select value={launchScope} onChange={(e) => setLaunchScope(e.target.value)} className="mt-1 block rounded-lg border border-slate-200 px-3 py-2 text-sm">
                <option value="CONSOLIDATED">Hợp nhất</option>
                <option value="PERSONAL">Cá nhân</option>
                <option value="BUSINESS">Doanh nghiệp</option>
              </select>
            </label>
            <button onClick={launch} disabled={launching} className="rounded-lg bg-teal-500 px-4 py-2 text-sm font-semibold text-white hover:bg-teal-600 disabled:opacity-50">
              {launching ? "Đang tạo..." : "+ Giao việc mới"}
            </button>
            {toast && <span className="text-xs text-teal-600">{toast}</span>}
          </div>

          <table className="w-full text-sm">
            <thead className="bg-slate-50 text-xs uppercase text-slate-400">
              <tr>
                <th className="px-4 py-3 text-left">#</th>
                <th className="px-4 py-3 text-left">Hành động / mục tiêu</th>
                <th className="px-4 py-3 text-left">Đòn bẩy</th>
                <th className="px-4 py-3 text-left">Agent đề xuất</th>
                <th className="px-4 py-3 text-left">Tác động tài chính</th>
                <th className="px-4 py-3 text-left">Deadline</th>
                <th className="px-4 py-3 text-left">Trạng thái</th>
                <th className="px-4 py-3 text-left">Thao tác</th>
              </tr>
            </thead>
            <tbody>
              {!loading &&
                filteredItems.map((item, idx) => {
                  const def = ACTIONS.find((a) => a.key === item.actionKey);
                  return (
                    <tr key={item.id} className="border-t border-slate-50 align-top">
                      <td className="px-4 py-3 text-slate-400">{idx + 1}</td>
                      <td className="max-w-xs px-4 py-3">
                        <div className="font-medium text-slate-700">
                          {def?.title}
                          {item.debtItem ? ` — ${item.debtItem.counterparty}` : ""}
                        </div>
                        {item.debtItem && (
                          <div className="text-xs text-slate-500">
                            Còn {formatVND(item.debtItem.amount - item.debtItem.collectedAmt)} · hạn {new Date(item.debtItem.dueDate).toLocaleDateString("vi-VN")}
                          </div>
                        )}
                        <div className="text-xs text-slate-400">{item.resultNote ?? def?.description}</div>
                        {item.evidence && <div className="mt-1 whitespace-pre-wrap rounded bg-slate-50 p-2 text-xs text-slate-400">{item.evidence}</div>}
                        {item.actualAmount !== 0 ? (
                          <>
                            <div className="mt-1.5 text-xs font-semibold text-teal-600">Kết quả thực tế: {formatVND(item.actualAmount)}</div>
                            {item.ceoNote && <div className="mt-1 text-[11px] italic text-slate-400">&ldquo;{item.ceoNote}&rdquo;</div>}
                          </>
                        ) : (
                          ["AWAITING_USER", "DONE"].includes(item.status) && <ActualAmountConfirm itemId={item.id} onSaved={load} />
                        )}
                      </td>
                      <td className="px-4 py-3 text-slate-500">
                        {item.actionKey}. {def?.title}
                      </td>
                      <td className="px-4 py-3 text-slate-500">{cfoRoleTitleForKey(item.actionKey)}</td>
                      <td className="px-4 py-3">
                        <div className="font-semibold text-teal-600">{item.expectedAmount > 0 ? formatVND(item.expectedAmount) : "—"}</div>
                        {item.confidence > 0 && <div className="text-[11px] text-slate-400">Khả năng: {Math.round(item.confidence * 100)}%</div>}
                      </td>
                      <td className="px-4 py-3 text-slate-500">{item.deadline ? new Date(item.deadline).toLocaleDateString("vi-VN") : "—"}</td>
                      <td className="px-4 py-3">
                        <span className={`rounded-full px-2.5 py-1 text-[11px] font-medium ${STATUS_STYLE[item.status]}`}>{STATUS_LABEL[item.status]}</span>
                      </td>
                      <td className="px-4 py-3">
                        <div className="flex flex-col gap-1.5">
                          {item.status === "PENDING" && (
                            <button onClick={() => assign(item.id)} className="rounded-lg border border-slate-200 px-2.5 py-1 text-xs hover:bg-slate-50">
                              Giao việc
                            </button>
                          )}
                          {["PENDING", "ASSIGNED", "AWAITING_USER", "FAILED"].includes(item.status) && (
                            <button onClick={() => run(item.id)} className="rounded-lg bg-teal-500 px-2.5 py-1 text-xs font-medium text-white hover:bg-teal-600">
                              Chạy Agent
                            </button>
                          )}
                          {["BLOCKED", "FAILED", "REVIEW"].includes(item.status) && (
                            <button onClick={() => analyze(item.id)} className="rounded-lg border border-violet-200 px-2.5 py-1 text-xs font-medium text-violet-600 hover:bg-violet-50">
                              Phân tích AI (Claude)
                            </button>
                          )}
                        </div>
                      </td>
                    </tr>
                  );
                })}
              {!loading && filteredItems.length === 0 && (
                <tr>
                  <td colSpan={8} className="px-4 py-6 text-center text-sm text-slate-400">
                    Chưa có nhiệm vụ nào khớp bộ lọc. Giao việc mới ở trên hoặc kích hoạt gợi ý từ Dashboard.
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>

        {/* Dự báo / cấu trúc thu chi / kết quả hiệu quả */}
        <div className="grid grid-cols-1 gap-6 lg:grid-cols-3">
          <div className="card p-5 lg:col-span-1">
            <div className="mb-1 flex items-center gap-2 font-bold text-slate-800">
              <ICONS.chart size={18} strokeWidth={1.75} className="text-slate-400" /> Dự báo dòng tiền
            </div>
            <p className="mb-2 text-[11px] text-slate-400">Cập nhật theo hành động trên — dùng lại forecastCashFlow của Dashboard.</p>
            {dash ? <ForecastLineChart points={dash.forecast?.base ?? []} shortfallDate={cfo?.shortfallDate ?? null} /> : <div className="py-10 text-center text-sm text-slate-400">Đang tải...</div>}
          </div>
          <div className="card p-5 lg:col-span-1">
            <div className="mb-1 flex items-center gap-2 font-bold text-slate-800">
              <ICONS.allocation size={18} strokeWidth={1.75} className="text-slate-400" /> Cấu trúc thu chi kỳ này
            </div>
            {dash ? <AllocationDonut data={dash.allocation ?? []} centerLabel={formatVNDCompact(dash.allocationTotal ?? 0)} /> : <div className="py-10 text-center text-sm text-slate-400">Đang tải...</div>}
          </div>
          <div className="card p-5 lg:col-span-1">
            <div className="mb-3 flex items-center gap-2 font-bold text-slate-800">
              <ICONS.verified size={18} strokeWidth={1.75} className="text-slate-400" /> Kết quả & hiệu quả hành động
            </div>
            <div className="grid grid-cols-2 gap-3 text-sm">
              <div className="rounded-xl bg-slate-50 p-3">
                <span className="mb-1 flex h-7 w-7 items-center justify-center rounded-lg bg-teal-50 text-teal-600">
                  <ICONS.inflow size={15} strokeWidth={1.75} />
                </span>
                <div className="text-[11px] text-slate-400">Tiền thu thêm</div>
                <div className="text-base font-bold text-teal-600">{formatVND(thuThem)}</div>
              </div>
              <div className="rounded-xl bg-slate-50 p-3">
                <span className="mb-1 flex h-7 w-7 items-center justify-center rounded-lg bg-sky-50 text-sky-600">
                  <ICONS.bank size={15} strokeWidth={1.75} />
                </span>
                <div className="text-[11px] text-slate-400">Tiền tiết kiệm</div>
                <div className="text-base font-bold text-teal-600">{formatVND(tietKiem)}</div>
              </div>
              <div className="rounded-xl bg-slate-50 p-3">
                <span className="mb-1 flex h-7 w-7 items-center justify-center rounded-lg bg-emerald-50 text-emerald-600">
                  <ICONS.verified size={15} strokeWidth={1.75} />
                </span>
                <div className="text-[11px] text-slate-400">Hành động hoàn thành</div>
                <div className="text-base font-bold text-slate-800">
                  {doneCount} / {launchedCount}
                </div>
              </div>
              <div className="rounded-xl bg-slate-50 p-3">
                <span className="mb-1 flex h-7 w-7 items-center justify-center rounded-lg bg-amber-50 text-amber-600">
                  <ICONS.forecast size={15} strokeWidth={1.75} />
                </span>
                <div className="text-[11px] text-slate-400">Cải thiện số dư</div>
                <div className="text-base font-bold text-slate-800">{formatVND(thuThem + tietKiem)}</div>
              </div>
            </div>
            {underperforming.length > 0 && (
              <div className="mt-3 flex flex-col gap-1.5 border-t border-slate-100 pt-3">
                <span className="text-[11px] font-medium text-amber-600">{underperforming.length} hành động cần điều chỉnh (Agent Chiến lược &amp; Hiệu quả)</span>
                {underperforming.map(({ item, verdict }) => {
                  const def = ACTIONS.find((a) => a.key === item.actionKey);
                  return (
                    <div key={item.id} className="rounded-lg bg-amber-50 px-2.5 py-2 text-xs text-amber-700">
                      <span className="font-medium">{def?.title}</span>
                      {item.debtItem ? ` — ${item.debtItem.counterparty}` : ""}: {verdict.note}
                    </div>
                  );
                })}
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
