import { Button } from "@/components/ui/button";
import {
    Tooltip,
    TooltipContent,
    TooltipProvider,
    TooltipTrigger,
} from "@/components/ui/tooltip";
import axios from "axios";
import { Octagon } from "lucide-react";
import { useState } from "react";
import { toast } from "sonner";

export default function StopServer(data: any) {
    const token = localStorage.getItem("auth_token");
    const [disable, setDisable] = useState(false);

    const handleStopServer = async (plant: string) => {
        toast.success(`${plant} is being stopped please wait.`);
        setDisable(true);
        let data: any = {
            processType: "stop",
            plantToken: plant,
        };

        const url: string = window.location.host.split(":")[0];
        if (url === "localhost" || url === "usmcd1vms036") {
            data = { ...data, remote: "true" };
        }

        //console.log(data);

        try {
            const res = await axios.post("/api/server/serviceprocess", data, {
                headers: { Authorization: `Bearer ${token}` },
            });

            //console.log(res);
            if (res.status === 200) {
                setTimeout(() => {
                    toast.success(`${plant} Has beed stopped.`);
                    setDisable(false);
                }, 3000);
            }
        } catch (error) {
            console.log(error);
        }
    };
    return (
        <div>
            <TooltipProvider>
                <Tooltip>
                    <TooltipTrigger asChild>
                        <Button
                            variant="destructive"
                            size={"icon"}
                            disabled={disable}
                            onClick={() =>
                                handleStopServer(data.plantData.plantToken)
                            }
                        >
                            <Octagon />
                        </Button>
                    </TooltipTrigger>
                    <TooltipContent>
                        <p>Stop Server</p>
                    </TooltipContent>
                </Tooltip>
            </TooltipProvider>
        </div>
    );
}
