"use client";

import { useEffect, useState } from "react";
import { useRouter, usePathname } from "next/navigation";
import Link from "next/link";

interface AdminUser {
  id: number;
  username: string;
  roles: string[];
  permissions: string[];
}

interface SidebarProps {
  user: AdminUser | null;
  loading: boolean;
  onLogout: () => void;
}

export default function Sidebar({ user, loading, onLogout }: SidebarProps) {
  const pathname = usePathname();

  const navItems = [
    {
      section: "概览",
      links: [{ href: "/dashboard", label: "仪表盘", icon: "◉" }],
    },
    {
      section: "平台数据",
      links: [
        { href: "/admin/workspaces", label: "Workspace", icon: "◎" },
        { href: "/admin/projects", label: "项目", icon: "◻" },
        { href: "/admin/rooms", label: "房间", icon: "◫" },
        { href: "/admin/repos", label: "仓库", icon: "◈" },
        { href: "/admin/ai", label: "AI 模型", icon: "◆" },
        { href: "/platform/users", label: "用户管理", icon: "◎" },
      ],
    },
    {
      section: "Admin 管理",
      links: [
        { href: "/admin/users", label: "Admin 用户", icon: "◈" },
        { href: "/admin/roles", label: "角色管理", icon: "◇" },
        { href: "/admin/permissions", label: "权限管理", icon: "○" },
      ],
    },
    {
      section: "系统",
      links: [
        { href: "/admin/logs", label: "审计日志", icon: "▣" },
        { href: "/platform/audit", label: "平台审计", icon: "☰" },
        { href: "/admin/sessions", label: "Admin 会话", icon: "◐" },
        { href: "/platform/sessions", label: "平台会话", icon: "☀" },
        { href: "/admin/api-tokens", label: "API Token", icon: "⚿" },
        { href: "/admin/daily-report", label: "每日报告", icon: "📧" },
      ],
    },
  ];

  return (
    <aside className="admin-sidebar">
      <div className="sidebar-logo">Admin</div>
      <nav className="sidebar-nav">
        {navItems.map((section) => (
          <div key={section.section} className="sidebar-section">
            <div className="sidebar-section-title">{section.section}</div>
            {section.links.map((link) => (
              <Link
                key={link.href}
                href={link.href}
                className={`sidebar-link ${pathname === link.href ? "active" : ""}`}
              >
                <span>{link.icon}</span>
                {link.label}
              </Link>
            ))}
          </div>
        ))}
      </nav>
      <div style={{ padding: "12px", borderTop: "1px solid #e5e5e5" }}>
        {loading ? (
          <div style={{ fontSize: "12px", color: "#737373", textAlign: "center" }}>验证中...</div>
        ) : user ? (
          <>
            <div style={{ fontSize: "12px", color: "#737373", marginBottom: "8px" }}>
              {user.username}
            </div>
            <button
              onClick={onLogout}
              className="btn btn-secondary btn-sm"
              style={{ width: "100%" }}
            >
              退出登录
            </button>
          </>
        ) : (
          <div style={{ fontSize: "12px", color: "#a3a3a3", textAlign: "center" }}>未登录</div>
        )}
      </div>
    </aside>
  );
}

export function useAdminAuth() {
  const router = useRouter();
  const [user, setUser] = useState<AdminUser | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch("/api/auth/me")
      .then((r) => r.json())
      .then((data) => {
        if (data.user) setUser(data.user);
      })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  async function handleLogout() {
    await fetch("/api/auth/logout", { method: "POST" });
    router.push("/login");
  }

  return { user, loading, handleLogout };
}
