import { useEffect, useMemo, useState } from "react";
import { Menu } from "antd";
import { SettingOutlined, TeamOutlined } from "@ant-design/icons";
import { Component } from "lucide-react";
import SystemConfig from "./SystemConfig";
import ModelAccess from "./ModelAccess";
import UserPermissionManagement from "./UserPermissionManagement";
import { useAppSelector } from "@/store/hooks";
import { hasPermission, PermissionCodes } from "@/auth/permissions";

export default function SettingsPage() {
  const permissions = useAppSelector((state) => state.auth.permissions);
  const canManageUsers = hasPermission(permissions, PermissionCodes.userManage);
  const canViewRoles = hasPermission(permissions, PermissionCodes.roleManage);
  const canViewPermissions = hasPermission(
    permissions,
    PermissionCodes.permissionManage
  );
  const tabs = useMemo(() => {
    const nextTabs = [
      {
        key: "model-access",
        icon: <Component className="w-4 h-4" />,
        label: "模型接入",
      },
      {
        key: "system-config",
        icon: <SettingOutlined />,
        label: "参数配置",
      },
    ];
    if (canManageUsers || canViewRoles || canViewPermissions) {
      nextTabs.push({
        key: "user-permission",
        icon: <TeamOutlined />,
        label: "用户与权限",
      });
    }
    return nextTabs;
  }, [canManageUsers, canViewPermissions, canViewRoles]);
  const [activeTab, setActiveTab] = useState<string>(tabs[0]?.key ?? "model-access");

  useEffect(() => {
    const hasActiveTab = tabs.some((tab) => tab.key === activeTab);
    if (!hasActiveTab && tabs.length > 0) {
      setActiveTab(tabs[0].key);
    }
  }, [activeTab, tabs]);

  return (
    <div className="h-screen flex">
      <div className="border-right h-full">
        {/* <h1 className="min-w-[200px] w-full border-bottom flex gap-2 text-lg font-bold text-gray-900 p-4">
          <Button icon={<X />} type="text" onClick={() => navigate(-1)} />
          设置中心
        </h1> */}
        <div className="h-full">
          <Menu
            mode="inline"
            items={tabs}
            selectedKeys={[activeTab]}
            onClick={({ key }) => {
              setActiveTab(String(key));
            }}
          />
        </div>
      </div>
      <div className="flex-1 h-full p-4">
        {/* 内容区域，根据 activeTab 渲染不同的组件 */}
        {activeTab === "system-config" && <SystemConfig />}
        {activeTab === "model-access" && <ModelAccess />}
        {activeTab === "user-permission" && (
          <UserPermissionManagement
            canManageUsers={canManageUsers}
            canViewRoles={canViewRoles}
            canViewPermissions={canViewPermissions}
          />
        )}
      </div>
    </div>
  );
}
