import React, { useState, useEffect } from 'react';
import { Layout as AntLayout, Menu, ConfigProvider, theme, Drawer, Button, Avatar, Dropdown } from 'antd';
import { RobotOutlined, MenuOutlined, AppstoreOutlined, EyeOutlined, SearchOutlined, UserOutlined, LogoutOutlined, WechatOutlined, TeamOutlined } from '@ant-design/icons';
import { useNavigate, useLocation, useSearchParams } from 'react-router-dom';
import ParticleBackground from './ParticleBackground';
import LoginModal from './LoginModal';
import ProfileModal from './ProfileModal';
import { motion, AnimatePresence } from 'framer-motion';
import { useAuth } from '../context/AuthContext';

const { Header, Content, Footer } = AntLayout;

const Layout = ({ children }) => {
  const navigate = useNavigate();
  const location = useLocation();
  const [searchParams] = useSearchParams();
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
  const [loginVisible, setLoginVisible] = useState(false);
  const [profileVisible, setProfileVisible] = useState(false);
  
  const { user, login, logout } = useAuth();

  // 全局监听并持久化 ref 参数
  useEffect(() => {
    const ref = searchParams.get('ref');
    if (ref) {
      console.log('[Layout] Capturing sales ref code:', ref);
      localStorage.setItem('ref_code', ref);
    }
  }, [searchParams]);

  const handleLogout = () => {
    logout();
    navigate('/');
  };

  const userMenu = {
    items: [
      {
        key: 'profile',
        label: '个人设置',
        icon: <UserOutlined />,
        onClick: () => setProfileVisible(true)
      },
      {
        key: 'logout',
        label: '退出登录',
        icon: <LogoutOutlined />,
        onClick: handleLogout
      }
    ]
  };

  const items = [
    {
      key: '/',
      icon: <RobotOutlined />,
      label: 'AI 硬件',
    },
    {
      key: '/forum',
      icon: <TeamOutlined />,
      label: '技术论坛',
    },
    {
      key: '/services',
      icon: <AppstoreOutlined />,
      label: 'AI 服务',
    },
    {
      key: '/courses',
      icon: <EyeOutlined />,
      label: 'VC 课程',
    },
    {
      key: '/my-orders',
      icon: <SearchOutlined />,
      label: '我的订单',
    },
  ];

  const handleMenuClick = (key) => {
    navigate(key);
    setMobileMenuOpen(false);
  };

  return (
    <ConfigProvider
      theme={{
        algorithm: theme.darkAlgorithm,
        token: {
          colorPrimary: '#00b96b',
          colorBgContainer: 'transparent',
          colorBgLayout: 'transparent',
          fontFamily: "'Orbitron', sans-serif",
        },
      }}
    >
      <ParticleBackground />
      <AntLayout style={{ minHeight: '100vh', background: 'transparent' }}>
        <Header 
          style={{ 
            position: 'fixed', 
            top: 0,
            left: 0,
            zIndex: 1000, 
            width: '100%', 
            padding: 0,
            background: 'rgba(0, 0, 0, 0.7)',
            backdropFilter: 'blur(20px)',
            borderBottom: '1px solid rgba(255, 255, 255, 0.1)',
            display: 'flex',
            height: '72px',
            lineHeight: '72px',
            boxShadow: '0 4px 30px rgba(0, 0, 0, 0.5)'
          }}
        >
          <div style={{ 
            width: '100%', 
            padding: '0 40px', 
            display: 'flex', 
            alignItems: 'center', 
            justifyContent: 'space-between',
            height: '100%'
          }}>
          <motion.div 
            initial={{ opacity: 0, x: -20 }}
            animate={{ opacity: 1, x: 0 }}
            transition={{ duration: 0.5 }}
            style={{ 
              color: '#fff', 
              fontSize: '20px', 
              fontWeight: 'bold', 
              display: 'flex', 
              alignItems: 'center', 
              cursor: 'pointer' 
            }}
            onClick={() => navigate('/')}
          >
            <img src="/liangji_logo.svg" alt="Quant Speed Logo" style={{ height: '40px', filter: 'invert(1) brightness(2)' }} />
          </motion.div>

          {/* Desktop Menu */}
          <div className="desktop-menu" style={{ display: 'none', flex: 1, justifyContent: 'flex-end', alignItems: 'center' }}>
            <Menu
              theme="dark"
              mode="horizontal"
              selectedKeys={[location.pathname]}
              items={items}
              onClick={(e) => handleMenuClick(e.key)}
              style={{ 
                background: 'transparent', 
                borderBottom: 'none', 
                display: 'flex', 
                justifyContent: 'flex-end',
                minWidth: '400px',
                marginRight: '20px'
              }}
            />
            
            {user ? (
              <div style={{ display: 'flex', alignItems: 'center', gap: 15 }}>
                {/* 小程序图标状态 */}
                <WechatOutlined 
                  style={{ 
                    fontSize: 24, 
                    color: user.openid && !user.openid.startsWith('web_') ? '#07c160' : '#666',
                    cursor: 'help'
                  }} 
                  title={user.openid && !user.openid.startsWith('web_') ? '已绑定微信小程序' : '未绑定微信小程序'}
                />
                
                <Dropdown menu={userMenu}>
                  <div style={{ display: 'flex', alignItems: 'center', cursor: 'pointer', color: '#fff' }}>
                    <Avatar src={user.avatar_url} icon={<UserOutlined />} style={{ marginRight: 8 }} />
                    <span>{user.nickname}</span>
                  </div>
                </Dropdown>
              </div>
            ) : (
              <Button type="primary" onClick={() => setLoginVisible(true)}>登录</Button>
            )}
          </div>
          <style>{`
            @media (min-width: 768px) {
              .desktop-menu { display: flex !important; }
              .mobile-menu-btn { display: none !important; }
            }
          `}</style>

          {/* Mobile Menu Button */}
          <Button 
            className="mobile-menu-btn"
            type="text" 
            icon={<MenuOutlined style={{ color: '#fff', fontSize: 20 }} />} 
            onClick={() => setMobileMenuOpen(true)}
          />
          </div>
        </Header>

        {/* Mobile Drawer Menu */}
        <Drawer
          title={<span style={{ color: '#00b96b' }}>导航菜单</span>}
          placement="right"
          onClose={() => setMobileMenuOpen(false)}
          open={mobileMenuOpen}
          styles={{ body: { padding: 0, background: '#111' }, header: { background: '#111', borderBottom: '1px solid #333' }, wrapper: { width: 250 } }}
        >
          <div style={{ padding: '20px', textAlign: 'center', borderBottom: '1px solid #333' }}>
            {user ? (
               <div style={{ color: '#fff' }}>
                 <Avatar 
                   src={user.avatar_url} 
                   icon={<UserOutlined />} 
                   size="large" 
                   style={{ marginBottom: 10, cursor: 'pointer' }} 
                   onClick={() => { setProfileVisible(true); setMobileMenuOpen(false); }}
                 />
                 <div onClick={() => { setProfileVisible(true); setMobileMenuOpen(false); }} style={{ cursor: 'pointer' }}>
                   {user.nickname}
                 </div>
                 <Button type="link" danger onClick={handleLogout} style={{ marginTop: 10 }}>退出登录</Button>
               </div>
            ) : (
              <Button type="primary" block onClick={() => { setLoginVisible(true); setMobileMenuOpen(false); }}>登录 / 注册</Button>
            )}
          </div>
          <Menu
            theme="dark"
            mode="vertical"
            selectedKeys={[location.pathname]}
            items={items}
            onClick={(e) => handleMenuClick(e.key)}
            style={{ background: 'transparent', borderRight: 'none' }}
          />
        </Drawer>

        <LoginModal 
          visible={loginVisible} 
          onClose={() => setLoginVisible(false)}
          onLoginSuccess={(userData) => login(userData)}
        />

        <ProfileModal 
          visible={profileVisible} 
          onClose={() => setProfileVisible(false)}
        />

        <Content style={{ marginTop: 72, padding: '40px 20px', overflowX: 'hidden' }}>
          <div style={{ 
            maxWidth: '1200px', 
            margin: '0 auto', 
            width: '100%',
            minHeight: 'calc(100vh - 128px)' 
          }}>
            <AnimatePresence mode="wait">
              <motion.div
                key={location.pathname}
                initial={{ opacity: 0, y: 20, filter: 'blur(10px)' }}
                animate={{ opacity: 1, y: 0, filter: 'blur(0px)' }}
                exit={{ opacity: 0, y: -20, filter: 'blur(10px)' }}
                transition={{ duration: 0.3 }}
              >
                {children}
              </motion.div>
            </AnimatePresence>
          </div>
        </Content>

        <Footer style={{ textAlign: 'center', background: 'rgba(0,0,0,0.5)', color: '#666', backdropFilter: 'blur(5px)' }}>
          Quant Speed AI Hardware ©{new Date().getFullYear()} Created by Quant Speed Tech
        </Footer>
      </AntLayout>
    </ConfigProvider>
  );
};

export default Layout;
