"use client";
import * as React from "react";
import {
  IconChartBar,
  IconDashboard,
  IconDatabase,
  IconInnerShadowTop,
  IconListDetails,
  IconUsers,
} from "@tabler/icons-react";

import { NavMain } from "@/components/nav-main";
import { NavUser } from "@/components/nav-user";
import {
  Sidebar,
  SidebarContent,
  SidebarFooter,
  SidebarHeader,
  SidebarMenu,
  SidebarMenuButton,
  SidebarMenuItem,
} from "@/components/ui/sidebar";

const navMain = [
  {
    title: "Dashboard",
    url: "/d/dashboard",
    icon: IconDashboard,
  },
  {
    title: "Tenant",
    url: "/d/tenant",
    icon: IconListDetails,
  },
  {
    title: "Bank",
    url: "/d/bank",
    icon: IconChartBar,
  },
  {
    title: "Database",
    url: "/d/database",
    icon: IconDatabase,
  },
  {
    title: "Users",
    url: "/d/user",
    icon: IconUsers,
  },
];

export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {
  const [user, setUser] = React.useState<any>(null);
  const [loading, setLoading] = React.useState(true);

  React.useEffect(() => {
    async function fetchUser() {
      try {
        setLoading(true);
        // token should be sent via cookie
        const token = localStorage.getItem("authToken");

        const headers: Record<string, string> = {};
        if (token) {
          headers["Authorization"] = `Bearer ${token}`;
        }
        const res = await fetch(process.env.NEXT_PUBLIC_API_URL + "/me", {
          headers,
        });
        const json = await res.json();
        // expects { result: { user_id, username } }'
        console.log({ json });
        console.log({
          name: json?.result?.username || "-",
          email: undefined,
          avatar: "/avatars/shadcn.jpg",
          user_id: json?.result?.user_id,
        });
        setUser({
          name: json?.result?.username || "-",
          email: undefined,
          avatar: "/avatars/shadcn.jpg",
          user_id: json?.result?.user_id,
        });
        console.log(user);
      } catch (e) {
        setUser(null);
      } finally {
        setLoading(false);
      }
    }
    fetchUser();
  }, []);

  return (
    <Sidebar collapsible="offcanvas" {...props}>
      <SidebarHeader>
        <SidebarMenu>
          <SidebarMenuItem>
            <SidebarMenuButton
              asChild
              className="data-[slot=sidebar-menu-button]:!p-1.5"
            >
              <a href="#">
                <IconInnerShadowTop className="!size-5" />
                <span className="text-base font-semibold">Midsuit</span>
              </a>
            </SidebarMenuButton>
          </SidebarMenuItem>
        </SidebarMenu>
      </SidebarHeader>
      <SidebarContent>
        <NavMain items={navMain} />
      </SidebarContent>
      <SidebarFooter>{!loading && <NavUser user={user} />}</SidebarFooter>
    </Sidebar>
  );
}
