"use client";

import { useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import { deleteClient, setClientArchived } from "@/app/admin/clients/[id]/actions";
import { Button } from "@/components/ui/button";

export function ClientActions({
  clientId,
  archived,
}: {
  clientId: string;
  archived: boolean;
}) {
  const [deleteStep, setDeleteStep] = useState(0);
  const [, startTransition] = useTransition();
  const router = useRouter();

  function handleArchive() {
    startTransition(async () => {
      await setClientArchived(clientId, !archived);
      router.refresh();
    });
  }

  function handleDelete() {
    if (deleteStep === 0) {
      setDeleteStep(1);
      return;
    }
    startTransition(async () => {
      await deleteClient(clientId);
    });
  }

  return (
    <div className="flex items-center gap-2 flex-wrap">
      <Button asChild variant="outline" size="sm">
        <a href={`/admin/clients/${clientId}/edit`}>Modifica</a>
      </Button>

      <Button variant="outline" size="sm" onClick={handleArchive}>
        {archived ? "Riattiva" : "Archivia"}
      </Button>

      {deleteStep === 0 ? (
        <Button
          variant="ghost"
          size="sm"
          onClick={handleDelete}
          className="text-red-400 hover:text-red-600"
        >
          Elimina
        </Button>
      ) : (
        <div className="flex items-center gap-1.5 bg-red-50 border border-red-200 rounded-lg px-3 py-1.5">
          <span className="text-xs text-red-700 font-medium">Eliminare definitivamente?</span>
          <button
            onClick={handleDelete}
            className="text-xs text-red-700 font-bold hover:text-red-900 underline ml-1"
          >
            Sì, elimina
          </button>
          <button
            onClick={() => setDeleteStep(0)}
            className="text-xs text-[#71717a] hover:text-[#1a1a1a] ml-1"
          >
            Annulla
          </button>
        </div>
      )}
    </div>
  );
}