import React, { useState, useEffect } from 'react';
import { Layout, Menu, Button, theme, Typography } from 'antd';
import {
  DashboardOutlined,
  UploadOutlined,
  AuditOutlined,
  BarChartOutlined,
  LogoutOutlined,
  FileTextOutlined,
  TeamOutlined,
  SettingOutlined,
  SafetyCertificateOutlined,
  HistoryOutlined,
  NotificationOutlined
} from '@ant-design/icons';
import { Outlet, useNavigate, useLocation } from 'react-router-dom';
import { maskPhone } from '../utils/phoneMask';

const { Header, Sider, Content } = Layout;
const { Title } = Typography;

const MainLayout = () => {
  const [collapsed] = useState(false);
  const [user, setUser] = useState(null);
  const navigate = useNavigate();
  const location = useLocation();
  const {
    token: { colorBgContainer, borderRadiusLG },
  } = theme.useToken();

  useEffect(() => {
    const userData = localStorage.getItem('user');
    if (!userData) {
      navigate('/login');
    } else {
      setUser(JSON.parse(userData));
    }
  }, [navigate]);

  const handleLogout = () => {
    localStorage.removeItem('token');
    localStorage.removeItem('user');
    navigate('/login');
  };

  const menuItems = [
    {
      key: '/dashboard',
      icon: <DashboardOutlined />,
      label: '首页概览',
    },
    {
      key: '/notifications',
      icon: <NotificationOutlined />,
      label: '系统公告',
    },
    {
      key: '/upload',
      icon: <UploadOutlined />,
      label: '成果上传',
    },
    ...((user?.role === 'admin' || user?.role === 'super_admin') ? [
      {
        key: '/audit',
        icon: <AuditOutlined />,
        label: '成果审核',
      }
    ] : []),
    ...((user?.role === 'super_admin' || user?.role === 'maintainer') ? [
      {
        key: '/users',
        icon: <TeamOutlined />,
        label: '用户管理',
      },
      {
        key: '/dictionaries',
        icon: <SettingOutlined />,
        label: '系统字典管理',
      },
      {
        key: '/validation',
        icon: <SafetyCertificateOutlined />,
        label: '数据校验',
      }
    ] : []),
    ...((user?.role === 'super_admin' || user?.role === 'maintainer') ? [
      {
        key: '/logs',
        icon: <HistoryOutlined />,
        label: '系统日志',
      }
    ] : []),
    ...((user?.role !== 'maintainer') ? [
      {
        key: '/statistics',
        icon: <BarChartOutlined />,
        label: '统计分析',
      },
    ] : []),
  ];
  
  // 过滤掉维护员不可见的菜单项
  if (user?.role === 'maintainer') {
    const hiddenKeys = ['/upload', '/dashboard', '/validation'];
    for (let i = menuItems.length - 1; i >= 0; i--) {
      if (hiddenKeys.includes(menuItems[i].key)) {
        menuItems.splice(i, 1);
      }
    }
  }

  return (
    <div style={{ display: 'flex', flexDirection: 'column', minHeight: '100vh' }}>
      <div className="marquee-container">
        <div className="marquee-content">
          温馨提示：本系统为内部使用，严禁上传涉密信息！上传内容将接受保密审查，违规行为将严肃处理。
        </div>
      </div>
      <Layout style={{ flex: 1 }}>
        <Sider 
          trigger={null} 
          collapsible 
        collapsed={collapsed} 
        theme="dark"
        width={256}
      >
        <div style={{ 
          height: 80, 
          margin: '16px', 
          display: 'flex', 
          alignItems: 'center', 
          justifyContent: collapsed ? 'center' : 'flex-start',
          padding: collapsed ? 0 : '0 16px',
          background: 'rgba(47, 0, 255, 0.05)',
          borderRadius: '12px',
          transition: 'all 0.2s',
          overflow: 'hidden'
        }}>
          <div style={{ 
            width: 40, 
            height: 40, 
            background: '#1677ff', 
            borderRadius: '8px',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            marginRight: collapsed ? 0 : 12,
            flexShrink: 0,
            overflow: 'hidden'
          }}>
            <img 
              src="/logo.png" 
              alt="Logo"
              style={{ width: '100%', height: '100%', objectFit: 'contain' }}
              onError={(e) => {
                e.target.style.display = 'none';
                e.target.nextSibling.style.display = 'block';
              }}
            />
            <FileTextOutlined style={{ color: 'white', fontSize: 22, display: 'none' }} />
          </div>
          {!collapsed && (
            <div style={{ overflow: 'hidden' }}>
              <Title level={5} style={{ color: 'white', margin: 0, fontSize: '16px', lineHeight: '1.2' }}>
                科技成果
              </Title>
              <div style={{ color: 'rgba(255,255,255,0.45)', fontSize: '12px' }}>管理系统</div>
            </div>
          )}
        </div>
        <Menu
          theme="dark"
          mode="inline"
          selectedKeys={[location.pathname]}
          items={menuItems}
          onClick={({ key }) => navigate(key)}
        />
      </Sider>
      <Layout>
        <Header style={{ padding: '0 16px', background: colorBgContainer, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <Title level={4} style={{ margin: 0 }}>欢迎, {user?.real_name || maskPhone(user?.username)}</Title>
          <Button 
            type="text" 
            icon={<LogoutOutlined />} 
            onClick={handleLogout}
          >
            退出登录
          </Button>
        </Header>
        <Content
          style={{
            margin: '24px 16px',
            padding: 24,
            minHeight: 280,
            background: colorBgContainer,
            borderRadius: borderRadiusLG,
            overflow: 'initial'
          }}
        >
          <Outlet />
        </Content>
        <div style={{ 
          textAlign: 'center', 
          padding: '16px 0', 
          background: colorBgContainer, 
          borderTop: '1px solid #f0f0f0',
          marginTop: 'auto'
        }}>
          <div>
          科技成果管理系统 V1.0 © 2026 黑龙江省自然资源权益调查监测院（黑龙江省自然资源卫星应用技术中心）保留所有权利
          </div>
        </div>
      </Layout>
      </Layout>
    </div>
  );
};

export default MainLayout;
