"use client";

import { useTransition } from "react";
import { useRouter } from "next/navigation";
import { deletePhase, deleteTask } from "@/app/admin/clients/[id]/actions";

interface DeletePhaseButtonProps {
  type: "phase";
  phaseId: string;
  clientId: string;
}

interface DeleteTaskButtonProps {
  type: "task";
  taskId: string;
  clientId: string;
}

type Props = DeletePhaseButtonProps | DeleteTaskButtonProps;

export function DeletePhaseTaskButton(props: Props) {
  const [, startTransition] = useTransition();
  const router = useRouter();

  function handleClick() {
    const label = props.type === "phase" ? "questa fase (e tutti i task/deliverable al suo interno)" : "questo task";
    if (!window.confirm(`Eliminare ${label}? L'azione non è reversibile.`)) return;

    startTransition(async () => {
      if (props.type === "phase") {
        await deletePhase(props.phaseId, props.clientId);
      } else {
        await deleteTask(props.taskId, props.clientId);
      }
      router.refresh();
    });
  }

  return (
    <button
      type="button"
      onClick={handleClick}
      title={props.type === "phase" ? "Elimina fase" : "Elimina task"}
      className="p-1 rounded text-[#999999] hover:text-red-500 hover:bg-red-50 transition-colors"
      aria-label={props.type === "phase" ? "Elimina fase" : "Elimina task"}
    >
      {/* Trash icon */}
      <svg
        className="w-3.5 h-3.5"
        fill="none"
        stroke="currentColor"
        strokeWidth={2}
        viewBox="0 0 24 24"
        aria-hidden="true"
      >
        <path strokeLinecap="round" strokeLinejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
      </svg>
    </button>
  );
}
