'use client';
import { useState, useEffect, createContext, useContext } from 'react';
import { useRouter, usePathname } from 'next/navigation';
import { getToken, clearToken, getUser, authFetch, ROLE_NAMES } from '@/lib/auth-client';
import './dashboard.css';

const UserContext = createContext(null);
export const useUser = () => useContext(UserContext);

const ALL_MENUS = [
  { key: 'dashboard', label: '工作台', icon: '📊', path: '/dashboard' },
  { key: 'contracts', label: '合同流转', icon: '📋', path: '/dashboard/contracts' },
  { key: 'partners', label: '合作单位', icon: '🏢', path: '/dashboard/partners' },
  { key: 'users', label: '用户管理', icon: '👥', path: '/dashboard/users' },
  { key: 'departments', label: '部门管理', icon: '🏛️', path: '/dashboard/departments' },
  { key: 'settings', label: '系统配置', icon: '⚙️', path: '/dashboard/settings' },
  { key: 'permissions', label: '权限配置', icon: '🔐', path: '/dashboard/permissions' },
];

export default function DashboardLayout({ children }) {
  const router = useRouter();
  const pathname = usePathname();
  const [user, setUser] = useState(null);
  const [permissions, setPermissions] = useState([]);
  const [collapsed, setCollapsed] = useState(false);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const token = getToken();
    if (!token) {
      router.replace('/login');
      return;
    }
    authFetch('/api/auth/me')
      .then(r => r.json())
      .then(data => {
        if (data.error) {
          clearToken();
          router.replace('/login');
          return;
        }
        setUser(data.user);
        setPermissions(data.permissions || []);
        setLoading(false);
      })
      .catch(() => {
        clearToken();
        router.replace('/login');
      });
  }, [router]);

  const handleLogout = () => {
    clearToken();
    router.replace('/login');
  };

  const visibleMenus = ALL_MENUS.filter(menu => {
    if (!user) return false;
    if (user.role === 'admin') return true;
    const perm = permissions.find(p => p.menu_key === menu.key);
    return perm ? perm.visible === 1 : false;
  });

  if (loading) {
    return (
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: '100vh' }}>
        <div className="loading-spinner"></div>
      </div>
    );
  }

  return (
    <UserContext.Provider value={user}>
      <div className="dashboard-layout">
        <aside className={`sidebar ${collapsed ? 'collapsed' : ''}`}>
          <div className="sidebar-header">
            <div className="sidebar-logo">📄</div>
            <span className="sidebar-brand">合同审批系统</span>
          </div>
          <nav className="sidebar-nav">
            {visibleMenus.map(menu => (
              <a
                key={menu.key}
                href={menu.path}
                className={`nav-item ${pathname === menu.path || (menu.key !== 'dashboard' && pathname.startsWith(menu.path)) ? 'active' : ''}`}
                onClick={(e) => { e.preventDefault(); router.push(menu.path); }}
              >
                <span className="nav-item-icon">{menu.icon}</span>
                <span className="nav-item-text">{menu.label}</span>
              </a>
            ))}
          </nav>
          <div className="sidebar-footer">
            <button className="sidebar-toggle" onClick={() => setCollapsed(!collapsed)}>
              {collapsed ? '→' : '← 收起菜单'}
            </button>
          </div>
        </aside>

        <div className={`main-content ${collapsed ? 'collapsed' : ''}`}>
          <header className="top-header">
            <div className="header-left">
              <span className="header-title">
                {visibleMenus.find(m => pathname === m.path || (m.key !== 'dashboard' && pathname.startsWith(m.path)))?.label || '工作台'}
              </span>
            </div>
            <div className="header-right">
              <div className="user-info">
                <div className="user-avatar">{user?.real_name?.[0]}</div>
                <div>
                  <div className="user-name">{user?.real_name}</div>
                  <span className="user-role">{ROLE_NAMES[user?.role] || user?.role}</span>
                </div>
              </div>
              <button className="logout-btn" onClick={handleLogout}>退出登录</button>
            </div>
          </header>
          <main className="page-content">
            {children}
          </main>
        </div>
      </div>
    </UserContext.Provider>
  );
}
