"use client";

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

export function CountryToggle({
  countryId,
  active,
}: {
  countryId: number;
  active: boolean;
}) {
  const router = useRouter();
  const [isActive, setIsActive] = useState(active);
  const [loading, setLoading] = useState(false);

  async function toggle() {
    setLoading(true);
    try {
      const res = await fetch(`/api/admin/countries/${countryId}/toggle`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ active: !isActive }),
      });
      if (res.ok) {
        setIsActive(!isActive);
        router.refresh();
      }
    } catch {
      // silent
    } finally {
      setLoading(false);
    }
  }

  return (
    <button
      onClick={toggle}
      disabled={loading}
      className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${
        isActive ? "bg-green-600" : "bg-surface-light"
      } ${loading ? "opacity-50" : ""}`}
    >
      <span
        className={`inline-block h-4 w-4 rounded-full bg-white transition-transform ${
          isActive ? "translate-x-6" : "translate-x-1"
        }`}
      />
    </button>
  );
}
