"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";

export default function DeleteFileButton({ token, name }: { token: string; name: string }) {
  const router = useRouter();
  const [loading, setLoading] = useState(false);

  async function handleDelete() {
    if (!confirm(`Delete "${name}"?\n\nThis permanently removes the file and cannot be undone.`)) return;
    setLoading(true);
    try {
      const res = await fetch(`/api/files/${token}`, { method: "DELETE" });
      if (res.ok) {
        router.push("/browse");
        router.refresh();
      } else {
        const data = await res.json().catch(() => ({})) as { error?: string };
        alert(data.error ?? `Delete failed (${res.status})`);
      }
    } catch {
      alert("Network error – could not delete file");
    } finally {
      setLoading(false);
    }
  }

  return (
    <button
      onClick={handleDelete}
      disabled={loading}
      className="flex w-full items-center justify-center gap-2.5 rounded-xl border py-3 text-sm font-semibold transition-all disabled:opacity-50"
      style={{
        borderColor: "rgba(239,68,68,0.3)",
        background: "rgba(239,68,68,0.06)",
        color: "#fca5a5",
      }}
    >
      {loading ? (
        <>
          <span className="w-4 h-4 rounded-full border border-rose-400 border-t-transparent animate-spin" />
          Deleting…
        </>
      ) : (
        <>
          <svg viewBox="0 0 24 24" className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden="true">
            <path strokeLinecap="round" strokeLinejoin="round" d="M14.74 9l-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 01-2.244 2.077H8.084a2.25 2.25 0 01-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 00-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 013.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 00-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 00-7.5 0" />
          </svg>
          Delete file
        </>
      )}
    </button>
  );
}
