'use client'
import {
  AlertDialog,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import { useState } from "react";
import { trpc } from "@/app/_trpc/client";
import { useToast } from "@/components/ui/use-toast";
import { Tool } from "@/server/tool/domain/models";

const AlertDeleteTools = ({selectedTools}:{selectedTools:Tool[]}) => {

  
  const utils = trpc.useUtils()
  const [open, setOpen] = useState<boolean>(false);
  const {toast}=useToast()
  const{mutate:deleteTools,isPending}=trpc.tools.deleteTools.useMutation({
    onSuccess:()=>{
      setOpen(false);
      utils.tools.getTools.invalidate()
    },
    onError:(err)=>{
      toast({
        title:'Error',
        description:'Error al eliminar herramienta',
        variant:'destructive'
      })
    }
  })
  

  const handledeleteTools = () => {
    const toolIds=selectedTools.map(tool=>tool.id)
    deleteTools({toolIds})
  };

  return (
    <AlertDialog open={open} onOpenChange={setOpen}>
      <AlertDialogTrigger asChild className="w-full">
      <Button variant="destructive" className="w-full " size="sm" disabled={selectedTools.length <= 0} >
            Eliminar
      </Button>
      </AlertDialogTrigger>
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>Seguro que desea eliminar este articulo?</AlertDialogTitle>
          <AlertDialogDescription>
            Esta accion no puede ser reversible, y será borrada permanentemente de este projecto
          </AlertDialogDescription>
        </AlertDialogHeader>
        <AlertDialogFooter>
          <AlertDialogCancel>Cancel</AlertDialogCancel>
          <Button variant="destructive"  disabled={selectedTools.length <= 0 || isPending}  onClick={() => handledeleteTools()}>
            Eliminar
          </Button>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  );
};

export default AlertDeleteTools;
