// ==========================================
// Backups — daily snapshots + manual snapshot + restore
// Reads from Supabase `backups` table.
// ==========================================

function BackupsPage({ state, setState, user }) {
  const toast = useToast();
  const [list, setList] = useState([]);
  const [loading, setLoading] = useState(true);
  const [busy, setBusy] = useState(false);
  const cloudMode = !!window.SUPA;
  const isPM = user && user.role === "pm";

  useEffect(() => {
    if (!cloudMode) { setLoading(false); return; }
    refresh();
  }, []);

  async function refresh() {
    setLoading(true);
    try {
      const data = await window.DB.listBackups(60);
      setList(data);
    } finally { setLoading(false); }
  }

  async function takeManualSnapshot() {
    if (!cloudMode) return;
    setBusy(true);
    try {
      const r = await window.DB.manualSnapshot(state);
      if (r.ok) {
        toast("📸 บันทึก snapshot สำเร็จ");
        refresh();
      } else {
        toast("บันทึก snapshot ล้มเหลว: " + (r.error || r.reason), "warn");
      }
    } finally { setBusy(false); }
  }

  async function restoreBackup(b) {
    if (!isPM) { toast("เฉพาะ PM เท่านั้นที่สามารถ restore", "warn"); return; }
    if (!confirm(`⚠ จะแทนที่ข้อมูลปัจจุบันทั้งหมดด้วย snapshot ของวันที่ ${fmtDateShort(b.snapshot_date)}\n\nข้อมูลที่แก้ไขหลังเวลานี้จะหายทั้งหมด\n\nต้องการดำเนินการต่อหรือไม่?`)) return;
    setBusy(true);
    try {
      const full = await window.DB.fetchBackup(b.id);
      if (!full) { toast("ไม่พบ backup", "warn"); return; }
      const restoredState = {
        ...state,
        projects: full.projects || [],
        materials: full.materials || [],
        transactions: full.transactions || [],
      };
      setState(restoredState);
      toast(`✓ Restore สำเร็จ — ใช้ข้อมูล snapshot ${fmtDateShort(b.snapshot_date)}`);
    } catch (e) {
      toast("Restore ล้มเหลว: " + e?.message, "warn");
    } finally { setBusy(false); }
  }

  async function removeBackup(b) {
    if (!isPM) { toast("เฉพาะ PM เท่านั้นที่ลบได้", "warn"); return; }
    if (!confirm(`ลบ snapshot ${fmtDateShort(b.snapshot_date)} (${b.trigger_kind})?`)) return;
    setBusy(true);
    try {
      await window.DB.deleteBackup(b.id);
      toast("ลบ snapshot แล้ว");
      refresh();
    } catch (e) {
      toast("ลบล้มเหลว: " + e?.message, "warn");
    } finally { setBusy(false); }
  }

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <h1>💾 Backup — Snapshot ข้อมูล</h1>
          <p className="muted">ระบบ backup อัตโนมัติทุกวัน + กดถ่าย snapshot ตอนใดก็ได้ · {isPM ? "PM สามารถ restore กลับได้" : "Restore เฉพาะ PM"}</p>
        </div>
        <button
          className="btn-primary"
          onClick={takeManualSnapshot}
          disabled={busy || !cloudMode}
          title="บันทึก snapshot ทันที (เช่น หลังเสร็จงานสำคัญ)"
        >
          📸 บันทึก Snapshot ทันที
        </button>
      </div>

      {!cloudMode && (
        <div className="alert-banner alert-warn">
          <span>⚠ Backup ใช้งานในโหมด Cloud เท่านั้น — โปรดเชื่อมต่อ Supabase ก่อน</span>
        </div>
      )}

      <div className="card no-pad" style={{ marginTop: 14 }}>
        <div className="table-wrap">
          <table className="data-table">
            <thead>
              <tr>
                <th style={{ width: "140px" }}>วันที่</th>
                <th style={{ width: "140px" }}>เวลาบันทึก</th>
                <th style={{ width: "100px" }}>ประเภท</th>
                <th>ผู้บันทึก</th>
                <th className="num-col">โครงการ</th>
                <th className="num-col">วัสดุ</th>
                <th className="num-col">ธุรกรรม</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              {loading && <tr><td colSpan="8" style={{ textAlign: "center", padding: 24 }}>กำลังโหลด...</td></tr>}
              {!loading && list.length === 0 && <tr><td colSpan="8"><Empty /></td></tr>}
              {!loading && list.map((b) => (
                <tr key={b.id}>
                  <td className="mono"><b>{fmtDateShort(b.snapshot_date)}</b></td>
                  <td className="mono small">{fmtDate(b.created_at)}</td>
                  <td>
                    {b.trigger_kind === "manual"
                      ? <span className="status-pill" style={{ background: "#fef3c7", color: "#92400e" }}>📸 Manual</span>
                      : <span className="status-pill" style={{ background: "#dbeafe", color: "#1e40af" }}>🤖 Auto</span>}
                  </td>
                  <td><b>{b.created_by_username || "—"}</b></td>
                  <td className="num-col">{fmtNum(b.meta?.counts?.projects || 0)}</td>
                  <td className="num-col">{fmtNum(b.meta?.counts?.materials || 0)}</td>
                  <td className="num-col">{fmtNum(b.meta?.counts?.transactions || 0)}</td>
                  <td>
                    <div className="row-actions">
                      {isPM && (
                        <button className="btn-ghost small" onClick={() => restoreBackup(b)} disabled={busy} title="Restore ข้อมูลกลับเป็น snapshot นี้">
                          ↩ Restore
                        </button>
                      )}
                      {isPM && (
                        <ConfirmBtn className="icon-btn danger" onConfirm={() => removeBackup(b)}>🗑</ConfirmBtn>
                      )}
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      <div className="muted small" style={{ marginTop: 12 }}>
        💡 ระบบสร้าง snapshot อัตโนมัติ <b>1 ครั้ง/วัน</b> เมื่อมีผู้เข้าใช้คนแรกในวันนั้น
        — หรือกด <b>📸 บันทึก Snapshot ทันที</b> เพื่อสร้าง manual snapshot
        · Restore = แทนที่ข้อมูลปัจจุบันด้วย snapshot (ของ ณ จุดนั้น)
      </div>
    </div>
  );
}
