import { banner_api } from "@/features/objects/lib/api";
import type { BannerListItem } from "@/features/objects/lib/data";
import { Button } from "@/shared/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/shared/ui/dialog";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { Loader2, Trash, X } from "lucide-react";
import { type Dispatch, type SetStateAction } from "react";
import { toast } from "sonner";

interface Props {
  opneDelete: boolean;
  setOpenDelete: Dispatch<SetStateAction<boolean>>;
  setDiscritDelete: Dispatch<SetStateAction<BannerListItem | null>>;
  discrit: BannerListItem | null;
}

const DeleteObject = ({
  opneDelete,
  setOpenDelete,
  setDiscritDelete,
  discrit,
}: Props) => {
  const queryClient = useQueryClient();

  const { mutate, isPending } = useMutation({
    mutationFn: (id: string) => banner_api.delete(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["banner_list"] });
      setOpenDelete(false);
      setDiscritDelete(null);
    },
    onError: () => {
      toast.error("Bannerni o'chirishda xatolik yuz berdi.");
    },
  });

  return (
    <Dialog open={opneDelete} onOpenChange={setOpenDelete}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Bannerni o'chirish</DialogTitle>
          <DialogDescription className="text-md font-semibold">
            Siz rostan ham bannerni o'chirmoqchimisiz?
          </DialogDescription>
        </DialogHeader>
        <DialogFooter>
          <Button
            className="bg-blue-600 cursor-pointer hover:bg-blue-600"
            onClick={() => setOpenDelete(false)}
          >
            <X />
            Bekor qilish
          </Button>
          <Button
            variant={"destructive"}
            onClick={() => discrit && mutate(discrit.id.toString())}
          >
            {isPending ? (
              <Loader2 className="animate-spin" />
            ) : (
              <>
                <Trash />
                O'chirish
              </>
            )}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};

export default DeleteObject;
