"use client";

import { useCallback, useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { Button, Layout, Menu, Typography } from "antd";
import {
  AuditOutlined,
  BarChartOutlined,
  DashboardOutlined,
  FileSearchOutlined,
  FileTextOutlined,
  FolderOutlined,
  InboxOutlined,
  LogoutOutlined,
  ShoppingOutlined,
  GlobalOutlined,
} from "@ant-design/icons";

import { authProvider } from "@/providers/auth-provider";

import { adminNavSelectedKey } from "./admin-shell-utils";

const { Sider } = Layout;

function readUserLabel(): string {
  if (typeof window === "undefined") return "";
  try {
    const raw = localStorage.getItem("authUser");
    if (!raw) return "Signed in";
    const u = JSON.parse(raw) as Record<string, unknown>;
    const email = typeof u.email === "string" ? u.email : null;
    const name = typeof u.name === "string" ? u.name : null;
    return email ?? name ?? "Signed in";
  } catch {
    return "Signed in";
  }
}

function readCmsUserRole(): string | null {
  if (typeof window === "undefined") return null;
  try {
    const raw = localStorage.getItem("authUser");
    if (!raw) return null;
    const u = JSON.parse(raw) as { role?: unknown };
    return typeof u.role === "string" ? u.role : null;
  } catch {
    return null;
  }
}

export function AdminSidebar() {
  const router = useRouter();
  const pathname = usePathname() ?? "/dashboard";
  const selected = adminNavSelectedKey(pathname);
  const [userLabel, setUserLabel] = useState("");

  useEffect(() => {
    queueMicrotask(() => {
      setUserLabel(readUserLabel());
    });
  }, []);

  const handleLogout = useCallback(async () => {
    const result = await authProvider.logout({});
    if (result.success && result.redirectTo) {
      router.replace(result.redirectTo);
    } else {
      router.replace("/login");
    }
  }, [router]);

  const menuItems = useMemo(() => {
    const role = readCmsUserRole();
    const premiumOps =
      role === "MANAGER" || role === "SUPER_ADMIN" ?
        [
          {
            key: "/dashboard/premium-ops",
            icon: <AuditOutlined className="text-indigo-200/70" />,
            label: <Link href="/dashboard/premium-ops">Premium Ops</Link>,
          },
        ]
      : [];

    return [
      {
        key: "/dashboard",
        icon: <DashboardOutlined className="text-indigo-200/70" />,
        label: <Link href="/dashboard">Dashboard</Link>,
      },
      ...premiumOps,
      {
        key: "/dashboard/posts",
        icon: <FileTextOutlined className="text-indigo-200/70" />,
        label: <Link href="/dashboard/posts">Posts</Link>,
      },
      {
        key: "/dashboard/categories",
        icon: <FolderOutlined className="text-indigo-200/70" />,
        label: <Link href="/dashboard/categories">Categories</Link>,
      },
      {
        key: "site-mgmt",
        icon: <GlobalOutlined className="text-indigo-200/70" />,
        label: "Quản lý website",
        children: [
          {
            key: "/dashboard/site/menu",
            label: <Link href="/dashboard/site/menu">Menu</Link>,
          },
          {
            key: "/dashboard/site/pages",
            label: <Link href="/dashboard/site/pages">Trang</Link>,
          },
          {
            key: "/dashboard/site/footer",
            label: <Link href="/dashboard/site/footer">Footer</Link>,
          },
        ],
      },
      {
        key: "/dashboard/analytics",
        icon: <BarChartOutlined className="text-indigo-200/70" />,
        label: <Link href="/dashboard/analytics">Analytics</Link>,
      },
      {
        key: "/dashboard/premium-orders",
        icon: <ShoppingOutlined className="text-indigo-200/70" />,
        label: <Link href="/dashboard/premium-orders">Premium orders</Link>,
      },
      {
        key: "/dashboard/premium-fulfillment-tasks",
        icon: <InboxOutlined className="text-indigo-200/70" />,
        label: <Link href="/dashboard/premium-fulfillment-tasks">Premium fulfillment</Link>,
      },
      {
        key: "/dashboard/expert-reviews",
        icon: <FileSearchOutlined className="text-indigo-200/70" />,
        label: <Link href="/dashboard/expert-reviews">Expert reviews</Link>,
      },
    ];
  }, [pathname]);

  return (
    <Sider
      breakpoint="lg"
      collapsible
      width={272}
      className="admin-shell-sider cms-dashboard-sider !border-r !border-white/[0.08]"
    >
      <div className="flex h-full min-h-0 flex-col">
        <div className="flex shrink-0 flex-col gap-1 border-b border-white/[0.08] px-5 py-6">
          <Typography.Title
            level={5}
            className="!m-0 !text-[15px] !font-semibold !leading-snug !tracking-tight text-white/95"
          >
            Co Thu Ky Pho
          </Typography.Title>
          <Typography.Text className="text-[12px] leading-snug text-indigo-200/55">
            CMS administrator
          </Typography.Text>
        </div>

        <div className="min-h-0 flex-1 overflow-y-auto px-1 py-4">
          <Menu
            theme="dark"
            mode="inline"
            selectedKeys={[selected]}
            className="!border-0 !bg-transparent"
            items={menuItems}
          />
        </div>

        <div className="shrink-0 border-t border-white/[0.08] px-4 py-4">
          <div className="mb-3 px-1">
            <Typography.Text className="block truncate text-[12px] font-medium text-white/80">
              {userLabel || "…"}
            </Typography.Text>
            <Typography.Text className="block text-[11px] text-indigo-200/40">Account</Typography.Text>
          </div>
          <Button
            type="default"
            block
            size="middle"
            icon={<LogoutOutlined />}
            className="!border-white/15 !bg-white/5 !text-white/85 hover:!border-white/25 hover:!bg-white/10 hover:!text-white"
            onClick={() => void handleLogout()}
          >
            Log out
          </Button>
        </div>
      </div>
    </Sider>
  );
}
