"use client";

import SitePage from "./SitePage";
import Loading from "@/components/Loading";

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import axios from "axios";
import Cookies from "js-cookie";
import { useParams } from "next/navigation";

export default function Dashboard() {
  const router = useRouter();
  const [loading, setLoading] = useState(true);
  const [username, setUsername] = useState("");
  const [name, setName] = useState("")
  const { siteId } = useParams();

  useEffect(() => {
    const init = async () => {
      const token = Cookies.get("token");
      if (!token) {
        router.push("/");
      }
      const response = await axios.post("/api/user/validate", { token });
      if (response.data.message !== "Valid") {
        Cookies.remove("token");
        router.push("/");
      } else {
        setUsername(response.data.username);
        setName(response.data.name);
        setLoading(false);
      }
    };
    init();
  }, []);

  if (loading) {
    return <Loading />;
  } else {
    return <SitePage username={username} name={name} siteId={siteId as string} />;
  }
}