"use client";

import { useState } from "react";
import { CurrencyInput } from "@/components/CurrencyInput";
import { fetchRetry } from "@/lib/httpRetry";

/**
 * Ghi nhận "Kết quả thực tế" — CHỈ do người dùng tự xác nhận số tiền thật đã cải thiện,
 * hệ thống không bao giờ tự suy đoán hay tự điền actualAmount. Dùng chung ở trang Hành động & Agent
 * và ở panel "Kết quả thực tế" trên Dashboard để không phải điều hướng sang trang khác mới ghi được.
 * Kèm 1 câu hỏi coaching ngắn ("Còn khó khăn gì?") — lưu vào ceoNote, tách khỏi resultNote/evidence
 * của Agent. Hoàn toàn tuỳ chọn, không bắt buộc chứng từ.
 */
export function ActualAmountConfirm({ itemId, label, onSaved }: { itemId: string; label?: string; onSaved: () => void }) {
  const [value, setValue] = useState("");
  const [note, setNote] = useState("");
  const [saving, setSaving] = useState(false);
  const [open, setOpen] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function confirm() {
    if (!value) return;
    setSaving(true);
    setError(null);
    try {
      const res = await fetchRetry(`/api/actions/${itemId}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ status: "DONE", actualAmount: Number(value), ceoNote: note.trim() || undefined }),
      });
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      setOpen(false);
      setValue("");
      setNote("");
      onSaved();
    } catch {
      setError("Lưu chưa thành công, thử lại lần nữa.");
    } finally {
      setSaving(false);
    }
  }

  if (!open) {
    return (
      <button onClick={() => setOpen(true)} className="mt-1.5 text-[11px] font-medium text-teal-600 hover:underline">
        + Ghi nhận kết quả thực tế{label ? ` — ${label}` : ""}
      </button>
    );
  }
  return (
    <div className="mt-1.5 flex flex-col gap-1.5">
      <div className="flex items-center gap-1.5">
        <CurrencyInput value={value} onChange={setValue} placeholder="Số tiền thực tế" className="w-28 rounded border border-slate-200 px-1.5 py-1 text-[11px]" />
        <button onClick={confirm} disabled={saving || !value} className="rounded bg-teal-500 px-2 py-1 text-[11px] font-medium text-white disabled:opacity-50">
          {saving ? "Đang lưu..." : "Lưu"}
        </button>
        <button onClick={() => setOpen(false)} className="text-[11px] text-slate-400 hover:underline">
          Huỷ
        </button>
      </div>
      <input
        value={note}
        onChange={(e) => setNote(e.target.value)}
        placeholder="Còn khó khăn gì? (tuỳ chọn)"
        className="w-full max-w-xs rounded border border-slate-200 px-1.5 py-1 text-[11px]"
      />
      {error && <span className="text-[11px] text-rose-500">{error}</span>}
    </div>
  );
}
