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

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

    const handleRestartServer = async (plant: string) => {
        toast.success(`${plant} is being restarted please wait.`);
        setDisable(true);
        let data: any = {
            processType: "restart",
            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 restarted.`);
                    setDisable(false);
                }, 3000);
            }
        } catch (error) {
            console.log(error);
        }
    };

    return (
        <div>
            <TooltipProvider>
                <Tooltip>
                    <TooltipTrigger asChild>
                        <Button
                            variant={"outline"}
                            size={"icon"}
                            disabled={disable}
                            onClick={() =>
                                handleRestartServer(data.plantData.plantToken)
                            }
                        >
                            <RotateCcw />
                        </Button>
                    </TooltipTrigger>
                    <TooltipContent>
                        <p>
                            Restart Server, note you might see the screen error
                            out for a second
                        </p>
                    </TooltipContent>
                </Tooltip>
            </TooltipProvider>
        </div>
    );
}
