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";

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

export default function ServerPage() {
    const { user, token } = useSessionStore();
    const { modules } = useModuleStore();
    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)) {
        router.navigate({ to: "/" });
    }

    if (isError) {
        return <div>{JSON.stringify(error)}</div>;
    }

    //console.log(data);
    return (
        <LstCard className="m-2 flex place-content-center w-dvh">
            <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">
                                        {server.sName}
                                    </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 />
                                                <StopServer
                                                    plantData={server}
                                                />
                                                <RestartServer />
                                            </div>
                                        )}
                                    </TableCell>
                                </TableRow>
                            );
                        })}
                    </TableBody>
                )}
            </Table>
        </LstCard>
    );
}
