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

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

    const handleStartServer = async (plant: string) => {
        toast.success(`${plant} is being started please wait.`);
        setDisable(true);
        let data: any = {
            processType: "start",
            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 started.`);
                    setDisable(false);
                }, 3000);
            }
        } catch (error: any) {
            if (error.status === 429) {
                toast.error(error.response.data.message);
                setDisable(false);
            }
        }
    };
    return (
        <div>
            <TooltipProvider>
                <Tooltip>
                    <TooltipTrigger asChild>
                        <Button
                            variant={"outline"}
                            size={"icon"}
                            disabled={disable}
                            onClick={() =>
                                handleStartServer(data.plantData.plantToken)
                            }
                        >
                            <Play />
                        </Button>
                    </TooltipTrigger>
                    <TooltipContent>
                        <p>Start Server</p>
                    </TooltipContent>
                </Tooltip>
            </TooltipProvider>
        </div>
    );
}
