"use client";

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

export default function GoldenToggle({ playerId, initial }: { playerId: string; initial: boolean }) {
  const [enabled, setEnabled] = useState(initial);
  const [loading, setLoading] = useState(false);
  const router = useRouter();

  async function toggle() {
    setLoading(true);
    const res = await fetch(`/api/admin/players/${playerId}/golden-toggle`, { method: "PATCH" });
    if (res.ok) {
      const data = await res.json();
      setEnabled(data.isGoldenCardEligible);
      router.refresh();
    }
    setLoading(false);
  }

  return (
    <button
      onClick={toggle}
      disabled={loading}
      title="Golden Card Eligible"
      className={`relative inline-flex h-5 w-9 items-center rounded-full transition-colors ${
        enabled ? "bg-yellow-400" : "bg-gray-300"
      } disabled:opacity-50`}
    >
      <span
        className={`inline-block h-3.5 w-3.5 transform rounded-full bg-white shadow transition-transform ${
          enabled ? "-translate-x-1" : "translate-x-1"
        }`}
      />
    </button>
  );
}
