"use client";

import { useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import { updateMicroOfferServices } from "@/app/admin/offers/actions";

export function ServiceCheckboxList({
  allServices,
  assignedIds,
  microId,
}: {
  allServices: Array<{ id: string; name: string; price: string }>;
  assignedIds: string[];
  microId: string;
}) {
  const [selected, setSelected] = useState(new Set(assignedIds));
  const [isPending, startTransition] = useTransition();
  const router = useRouter();

  function toggle(serviceId: string) {
    const next = new Set(selected);
    if (next.has(serviceId)) next.delete(serviceId);
    else next.add(serviceId);
    setSelected(next);
    startTransition(async () => {
      await updateMicroOfferServices(microId, [...next]);
      router.refresh();
    });
  }

  return (
    <div className="space-y-1">
      {allServices.map((svc) => (
        <label key={svc.id} className="flex items-center gap-2 cursor-pointer text-sm">
          <input
            type="checkbox"
            checked={selected.has(svc.id)}
            onChange={() => toggle(svc.id)}
            disabled={isPending}
            className="rounded"
          />
          <span>{svc.name}</span>
          <span className="ml-auto text-xs text-[#71717a]">€{parseFloat(svc.price).toFixed(2)}</span>
        </label>
      ))}
      {allServices.length === 0 && (
        <p className="text-xs text-[#71717a]">Nessun servizio nel catalogo ancora.</p>
      )}
    </div>
  );
}
