"use client";

import { useRef } from "react";
import { Button } from "@/components/ui/button";
import { ConfirmButton } from "./confirm-button";
import {
  Dialog,
  DialogClose,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { invoke } from "@tauri-apps/api/core";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";

type DeleteDialogProps = {
  id: string;
  open: boolean;
  onOpenChange: (open: boolean) => void;
};

export default function DeleteDialog({
  id,
  open,
  onOpenChange,
}: DeleteDialogProps) {
  const formRef = useRef<HTMLFormElement>(null);
  const queryClient = useQueryClient();

  const delete_app = async (id: string) => {
    await invoke("delete_apps", { id });
  };

  const { mutate: deleteApp } = useMutation({
    mutationKey: ["delete_app"],
    mutationFn: delete_app,
    onSuccess: () => {
      console.log("App deleted successfully");
      queryClient.invalidateQueries({ queryKey: ["apps"] });
    },
    onError: (error) => {
      toast.error("Error deleting app");
      console.error("Error deleting app:", error);
    },
  });

  const handleDelete = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    deleteApp(id);
    onOpenChange(false);
  };

  const handleHoldComplete = () => {
    if (formRef.current) {
      formRef.current.requestSubmit();
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <form ref={formRef} onSubmit={handleDelete}>
        <DialogContent className="sm:max-w-sm">
          <DialogHeader>
            <DialogTitle>Delete App</DialogTitle>
            <DialogDescription>
              Are you sure you want to delete this app? This action cannot be
              undone.
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <DialogClose asChild>
              <Button variant="outline">Cancel</Button>
            </DialogClose>
            <ConfirmButton text="Confirm" onConfirm={handleHoldComplete} />
          </DialogFooter>
        </DialogContent>
      </form>
    </Dialog>
  );
}
