"use client";

import { Skeleton } from "@/components/ui/skeleton";
import { useApp } from "@/context/app";
import { useGlobal } from "@/context/global";
import { sideNavLinks } from "@/models/app";
import { SideNavLink } from "@/types/app";
import { useEffect, useState } from "react";
import { RenderLink } from "./_renderlink";

export default function SideNav() {
  const { activeSession } = useApp();
  const { permissions } = activeSession;

  const { dict } = useGlobal();

  const [links, setLinks] = useState<SideNavLink[]>([]);

  useEffect(() => {
    if (!activeSession?.permissions) return;

    setLinks(
      sideNavLinks({ dict, canViewUserList: permissions.canViewUserList() }),
    );

    return () => {
      setLinks([]);
    };
  }, [permissions]);

  return (
    <>
      <div className="w-fit max-w-[150px] space-y-2 bg-white shadow [&>a]:block">
        {links.length > 0
          ? links.map((l, i) => (
              <RenderLink
                key={i}
                link={l.link}
                icon={l.icon}
                tooltip={l.tooltip}
              />
            ))
          : Array.from({ length: 3 }).map((_, i) => (
              <Skeleton key={i} className="mx-2 h-10 w-[50px] rounded" />
            ))}
      </div>
    </>
  );
}
