import { Button } from "@/components/ui/button";
import { CircleFadingArrowUp } from "lucide-react";
import { toast } from "sonner";
import { Servers } from "./ServerPage";
import { useQuery } from "@tanstack/react-query";
import { getSettings } from "@/utils/querys/settings";
import axios from "axios";
import {
    Tooltip,
    TooltipContent,
    TooltipProvider,
    TooltipTrigger,
} from "@/components/ui/tooltip";

export default function UpdateServer({
    server,
    token,
}: {
    server: Servers;
    token: string;
}) {
    const { data } = useQuery(getSettings(token ?? ""));
    const upgrade = async () => {
        let devDir = data.filter((n: any) => n.name === "devDir");
        toast.success("Server being upgraded in the background please wait.");
        try {
            const result = await axios.post(
                `/api/server/update/${server.plantToken}`,
                { devDir: devDir[0].value },
                {
                    headers: { Authorization: `Bearer ${token}` },
                }
            );

            if (result.data.success) {
                toast.success(result.data.message);
            }

            if (!result.data.success) {
                toast.success(result.data.message);
            }
        } catch (error: any) {
            toast.error(
                `There was an error updating the server: ${error.data.message}`
            );
        }
    };
    return (
        <div>
            <TooltipProvider>
                <Tooltip>
                    <TooltipTrigger asChild>
                        <Button
                            variant={`${server.isUpgrading ? "ghost" : "outline"}`}
                            size={"icon"}
                            onClick={upgrade}
                            disabled={server.isUpgrading}
                        >
                            <CircleFadingArrowUp />
                        </Button>
                    </TooltipTrigger>
                    <TooltipContent>
                        <p>Update {server.sName}</p>
                    </TooltipContent>
                </Tooltip>
            </TooltipProvider>
        </div>
    );
}
