"use client";

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

export default function DeleteRoundButton({ roundId, hasMatches }: { roundId: string; hasMatches: boolean }) {
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const [showConfirm, setShowConfirm] = useState(false);

  async function handleDelete() {
    setLoading(true);
    const res = await fetch("/api/rounds", {
      method: "DELETE",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ id: roundId }),
    });
    
    if (res.ok) {
      router.refresh();
    } else {
      const data = await res.json();
      alert(data.error || "خطا در حذف");
    }
    setLoading(false);
    setShowConfirm(false);
  }

  if (hasMatches) {
    return (
      <button disabled
        className="bg-gray-300 text-gray-500 px-3 py-1.5 rounded-lg text-sm cursor-not-allowed"
        title="دور دارای بازی است">
        حذف
      </button>
    );
  }

  return (
    <>
      <button onClick={() => setShowConfirm(true)}
        className="bg-red-600 text-white px-3 py-1.5 rounded-lg text-sm hover:bg-red-700 transition">
        حذف
      </button>
      
      {showConfirm && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50" onClick={() => setShowConfirm(false)}>
          <div className="bg-white rounded-2xl p-6 max-w-sm mx-4" onClick={(e) => e.stopPropagation()}>
            <h3 className="text-lg font-bold mb-3">حذف دور</h3>
            <p className="text-gray-600 mb-6">آیا مطمئن هستید که می‌خواهید این دور را حذف کنید؟</p>
            <div className="flex gap-3">
              <button onClick={handleDelete} disabled={loading}
                className="flex-1 bg-red-600 text-white py-2 rounded-xl font-bold hover:bg-red-700 transition disabled:opacity-50">
                {loading ? "در حال حذف..." : "بله، حذف شود"}
              </button>
              <button onClick={() => setShowConfirm(false)}
                className="flex-1 bg-gray-200 text-gray-700 py-2 rounded-xl font-bold hover:bg-gray-300 transition">
                انصراف
              </button>
            </div>
          </div>
        </div>
      )}
    </>
  );
}
