"use client";

import { useRef, useState } from "react";

export function BackupRestoreButtons() {
  const [restoring, setRestoring] = useState(false);
  const [status, setStatus] = useState<{ ok: boolean; msg: string } | null>(null);
  const inputRef = useRef<HTMLInputElement>(null);

  async function handleFileChange(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (!file) return;

    const confirmed = window.confirm(
      "RESTORE BACKUP\n\nThis will permanently replace ALL existing properties, brokers, areas, and photos with the data from the selected file.\n\nEnquiry/lead records will be deleted.\n\nContinue?"
    );
    if (!confirmed) {
      e.target.value = "";
      return;
    }

    setRestoring(true);
    setStatus(null);

    const form = new FormData();
    form.append("backup", file);

    try {
      const res = await fetch("/api/admin/restore", { method: "POST", body: form });
      const json = await res.json();
      if (res.ok) {
        setStatus({ ok: true, msg: `Restored: ${json.counts.properties} properties, ${json.counts.photos} photos, ${json.counts.brokers} brokers. Reloading…` });
        setTimeout(() => window.location.reload(), 2000);
      } else {
        setStatus({ ok: false, msg: json.error ?? "Restore failed" });
      }
    } catch {
      setStatus({ ok: false, msg: "Network error — restore failed" });
    } finally {
      setRestoring(false);
      if (inputRef.current) inputRef.current.value = "";
    }
  }

  return (
    <div className="flex flex-wrap items-center gap-2">
      {status && (
        <span className={`text-sm ${status.ok ? "text-emerald-700" : "text-red-700"}`}>
          {status.msg}
        </span>
      )}

      <a
        href="/api/admin/backup"
        className="rounded border border-stone-300 bg-white px-4 py-2 text-sm font-semibold text-stone-700 hover:bg-stone-50"
        download
      >
        ↓ Backup
      </a>

      <label
        className={`cursor-pointer rounded border border-stone-300 bg-white px-4 py-2 text-sm font-semibold text-stone-700 hover:bg-stone-50 ${restoring ? "pointer-events-none opacity-50" : ""}`}
      >
        {restoring ? "Restoring…" : "↑ Restore"}
        <input
          ref={inputRef}
          type="file"
          accept=".zip,.json"
          className="sr-only"
          onChange={handleFileChange}
          disabled={restoring}
        />
      </label>
    </div>
  );
}
