import { LstCard } from "@/components/extendedUI/LstCard";
import { Skeleton } from "@/components/ui/skeleton";
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from "@/components/ui/table";
import { useSessionStore } from "@/lib/store/sessionStore";
import { useModuleStore } from "@/lib/store/useModuleStore";
import { getServers } from "@/utils/querys/servers";
import { useQuery } from "@tanstack/react-query";
import { useRouter } from "@tanstack/react-router";
import { format } from "date-fns";
import UpdateServer from "./UpdateServer";
import { adminUrlCheck } from "@/utils/adminUrlCheck";
import RestartServer from "./RestartServer";
import StopServer from "./StopServer";
import StartServer from "./StartServer";
import { Button } from "@/components/ui/button";
import { getSettings } from "@/utils/querys/settings";
import { toast } from "sonner";
import axios from "axios";
import { useEffect } from "react";
//import { useState } from "react";

export type Servers = {
    server_id?: string;
    sName?: string;
    serverDNS?: string;
    plantToken?: string;
    idAddress: string;
    lastUpdated: string;
    isUpgrading: boolean;
    lstServerPort: string;
};

export default function ServerPage() {
    const { user, token } = useSessionStore();
    const { modules } = useModuleStore();
    //const [upgrading, setUpgrading] = useState(false);
    const router = useRouter();

    const { data, isError, error, isLoading } = useQuery(
        getServers(token ?? "")
    );

    // const adminModule = modules.filter((n) => n.name === "admin");
    // const userLevel =
    //     user?.roles?.filter((r) => r.module_id === adminModule[0].module_id) ||
    //     [];

    // if (!adminModule[0]?.roles?.includes(userLevel[0]?.role)) {
    //     console.log("Something failed");
    //     //router.navigate({ to: "/" });
    // }

    useEffect(() => {
        if (!user || modules.length === 0) return;

        const adminModule = modules.find((n) => n.name === "admin");
        if (!adminModule) {
            console.log("no module loaded");
            //router.navigate({ to: "/" });
            return;
        }

        const userLevel =
            user?.roles?.filter((r) => r.module_id === adminModule.module_id) ||
            [];

        if (!adminModule.roles?.includes(userLevel[0]?.role)) {
            console.log("Something failed");
            //router.navigate({ to: "/" });
        }
    }, [modules, user, router]);

    if (isError) {
        return <div>{JSON.stringify(error)}</div>;
    }
    const { data: set } = useQuery(getSettings(token ?? ""));
    const upgrade = async () => {
        let devDir = set.filter((n: any) => n.name === "devDir");
        toast.success("All Servers was just triggered.");

        try {
            const result = await axios.post(
                `/api/server/update/localhost`,
                { devDir: devDir[0].value, all: true },
                {
                    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}`
            );
        }
    };

    //console.log(data);
    return (
        <LstCard className="m-2 flex place-content-center w-dvh">
            <div className="flex justify-end m-2">
                <Button
                    onClick={upgrade}
                    disabled={data?.some((d: any) => d.isUpgrading)}
                >
                    Update All Servers
                </Button>
            </div>
            <Table>
                <TableHeader>
                    <TableRow>
                        <TableHead>Name</TableHead>
                        <TableHead>Server</TableHead>
                        <TableHead>PlantToken</TableHead>
                        <TableHead>IP Address</TableHead>
                        <TableHead>Date Last updated</TableHead>
                        <TableHead>Update Server</TableHead>
                    </TableRow>
                </TableHeader>
                {isLoading ? (
                    <>
                        <TableBody>
                            {Array(10)
                                .fill(0)
                                .map((_, i) => (
                                    <TableRow key={i}>
                                        <TableCell className="font-medium">
                                            <Skeleton className="h-4" />
                                        </TableCell>
                                        <TableCell>
                                            <Skeleton className="h-4" />
                                        </TableCell>
                                        <TableCell>
                                            <Skeleton className="h-4" />
                                        </TableCell>
                                        <TableCell>
                                            <Skeleton className="h-4" />
                                        </TableCell>
                                    </TableRow>
                                ))}
                        </TableBody>
                    </>
                ) : (
                    <TableBody>
                        {data?.map((server: Servers) => {
                            const strippedDate = server.lastUpdated.replace(
                                "Z",
                                ""
                            ); // Remove Z
                            const formattedDate = format(
                                strippedDate,
                                "MM/dd/yyyy hh:mm a"
                            );
                            return (
                                <TableRow key={server.server_id}>
                                    <TableCell className="font-medium">
                                        <a
                                            href={`http://${server.serverDNS}:${server.lstServerPort}`}
                                            target={"_blank"}
                                        >
                                            <span>{server.sName}</span>
                                        </a>
                                    </TableCell>
                                    <TableCell className="font-medium">
                                        {server.serverDNS}
                                    </TableCell>
                                    <TableCell className="font-medium">
                                        {server.plantToken}
                                    </TableCell>
                                    <TableCell className="font-medium">
                                        {server.idAddress}
                                    </TableCell>
                                    <TableCell className="font-medium">
                                        {formattedDate}
                                    </TableCell>
                                    <TableCell className="font-medium">
                                        {adminUrlCheck() && (
                                            <div className="flex flex-row">
                                                <UpdateServer
                                                    server={server}
                                                    token={token as string}
                                                />

                                                <StartServer
                                                    plantData={server}
                                                />
                                                <StopServer
                                                    plantData={server}
                                                />

                                                <RestartServer
                                                    plantData={server}
                                                />
                                            </div>
                                        )}
                                    </TableCell>
                                </TableRow>
                            );
                        })}
                    </TableBody>
                )}
            </Table>
        </LstCard>
    );
}
