import React, { useState, useEffect } from 'react';
import { useRouter } from 'next/router';
import Head from 'next/head';
import { Users, Package, MessageSquare, BarChart3, Settings, Home, CreditCard, Menu, X } from 'lucide-react';

interface AdminLayoutProps {
  children: React.ReactNode;
  darkMode: boolean;
  setDarkMode: (value: boolean) => void;
  currentPage: string;
}

const navItems = [
  { id: 'dashboard', label: 'Dashboard', icon: BarChart3, href: '/admin' },
  { id: 'users', label: 'Users', icon: Users, href: '/admin/users' },
  { id: 'packages', label: 'Packages', icon: Package, href: '/admin/packages' },
  { id: 'payments', label: 'Payments', icon: CreditCard, href: '/admin/payments' },
];

export default function AdminLayout({ children, darkMode, setDarkMode, currentPage }: AdminLayoutProps) {
  const router = useRouter();
  const [sidebarOpen, setSidebarOpen] = useState(false);
  const [isMobile, setIsMobile] = useState(false);

  useEffect(() => {
    const checkMobile = () => setIsMobile(window.innerWidth < 768);
    checkMobile();
    window.addEventListener('resize', checkMobile);
    return () => window.removeEventListener('resize', checkMobile);
  }, []);

  const theme = {
    bg: darkMode ? '#1a1a2e' : '#f8fafc',
    sidebarBg: darkMode ? '#16213e' : '#ffffff',
    cardBg: darkMode ? '#16213e' : '#ffffff',
    text: darkMode ? '#e2e8f0' : '#1e293b',
    textSecondary: darkMode ? '#94a3b8' : '#64748b',
    textMuted: darkMode ? '#64748b' : '#9ca3af',
    border: darkMode ? '#2d3748' : '#e2e8f0',
    hoverBg: darkMode ? '#1f2d3d' : '#f1f5f9',
    activeBg: darkMode ? '#2d3748' : '#e2e8f0',
  };

  const S: Record<string, React.CSSProperties> = {
    container: {
      display: 'flex',
      minHeight: '100vh',
      background: theme.bg,
    },
    sidebar: {
      width: 240,
      background: theme.sidebarBg,
      borderRight: `1px solid ${theme.border}`,
      display: 'flex',
      flexDirection: 'column',
      position: 'fixed',
      top: 0,
      left: isMobile ? (sidebarOpen ? 0 : -240) : 0,
      height: '100vh',
      zIndex: 100,
      transition: 'left 0.3s ease',
    },
    overlay: {
      position: 'fixed',
      top: 0,
      left: 0,
      right: 0,
      bottom: 0,
      background: 'rgba(0,0,0,0.5)',
      zIndex: 99,
      display: isMobile && sidebarOpen ? 'block' : 'none',
    },
    mobileHeader: {
      display: isMobile ? 'flex' : 'none',
      alignItems: 'center',
      justifyContent: 'space-between',
      padding: '12px 16px',
      background: theme.sidebarBg,
      borderBottom: `1px solid ${theme.border}`,
      position: 'sticky',
      top: 0,
      zIndex: 50,
    },
    menuBtn: {
      padding: 8,
      borderRadius: 8,
      border: `1px solid ${theme.border}`,
      background: 'transparent',
      color: theme.text,
      cursor: 'pointer',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
    },
    sidebarHeader: {
      padding: '20px 16px',
      borderBottom: `1px solid ${theme.border}`,
    },
    logo: {
      fontSize: 20,
      fontWeight: 700,
      background: 'linear-gradient(90deg, #2563eb, #7c3aed)',
      WebkitBackgroundClip: 'text',
      WebkitTextFillColor: 'transparent',
      display: 'flex',
      alignItems: 'center',
      gap: 8,
    },
    nav: {
      flex: 1,
      padding: '16px 8px',
      display: 'flex',
      flexDirection: 'column',
      gap: 4,
    },
    navItem: {
      display: 'flex',
      alignItems: 'center',
      gap: 12,
      padding: '10px 12px',
      borderRadius: 8,
      cursor: 'pointer',
      transition: 'all 0.2s',
      fontSize: 14,
      fontWeight: 500,
      textDecoration: 'none',
    },
    sidebarFooter: {
      padding: 16,
      borderTop: `1px solid ${theme.border}`,
    },
    main: {
      flex: 1,
      marginLeft: isMobile ? 0 : 240,
      padding: isMobile ? 16 : 24,
      minHeight: '100vh',
      width: isMobile ? '100%' : 'auto',
    },
    header: {
      display: 'flex',
      justifyContent: 'space-between',
      alignItems: 'center',
      marginBottom: 24,
    },
    title: {
      fontSize: 24,
      fontWeight: 700,
      color: theme.text,
    },
    headerButtons: {
      display: 'flex',
      gap: 12,
    },
    themeBtn: {
      padding: '8px 16px',
      borderRadius: 8,
      border: `1px solid ${theme.border}`,
      background: theme.cardBg,
      color: theme.text,
      cursor: 'pointer',
      fontSize: 14,
    },
    backBtn: {
      padding: '8px 16px',
      borderRadius: 8,
      border: `1px solid ${theme.border}`,
      background: theme.cardBg,
      color: theme.text,
      cursor: 'pointer',
      fontSize: 14,
      display: 'flex',
      alignItems: 'center',
      gap: 8,
    },
  };

  function toggleTheme() {
    const newMode = !darkMode;
    setDarkMode(newMode);
    try { localStorage.setItem('theme', newMode ? 'dark' : 'light'); } catch {}
  }

  return (
    <>
      <Head>
        <title>Admin - Gregory AI</title>
        <meta name="robots" content="noindex, nofollow" />
      </Head>
      <style>{`
        body { margin: 0; padding: 0; background: ${theme.bg}; }
        html { background: ${theme.bg}; }
        ::placeholder { color: ${theme.textMuted}; }
      `}</style>

      <div style={S.container}>
        {/* Mobile Header */}
        <div style={S.mobileHeader as any}>
          <button style={S.menuBtn as any} onClick={() => setSidebarOpen(true)}>
            <Menu size={20} />
          </button>
          <div style={S.logo}>⚡ Admin</div>
          <button style={S.menuBtn as any} onClick={toggleTheme}>
            {darkMode ? '☀️' : '🌙'}
          </button>
        </div>

        {/* Overlay */}
        <div style={S.overlay as any} onClick={() => setSidebarOpen(false)} />

        {/* Sidebar */}
        <aside style={S.sidebar as any}>
          <div style={S.sidebarHeader}>
            <div style={S.logo}>
              ⚡ Admin Panel
            </div>
          </div>

          <nav style={S.nav}>
            {navItems.map((item) => {
              const Icon = item.icon;
              const isActive = currentPage === item.id || 
                (item.id === 'users' && currentPage === 'users') ||
                (item.id === 'dashboard' && router.pathname === '/admin');
              
              return (
                <div
                  key={item.id}
                  onClick={() => { router.push(item.href); setSidebarOpen(false); }}
                  style={{
                    ...S.navItem,
                    background: isActive ? theme.activeBg : 'transparent',
                    color: isActive ? theme.text : theme.textSecondary,
                  }}
                  onMouseEnter={(e) => {
                    if (!isActive) e.currentTarget.style.background = theme.hoverBg;
                  }}
                  onMouseLeave={(e) => {
                    if (!isActive) e.currentTarget.style.background = 'transparent';
                  }}
                >
                  <Icon size={18} />
                  {item.label}
                </div>
              );
            })}
          </nav>

          <div style={S.sidebarFooter}>
            <div
              onClick={() => { router.push('/'); setSidebarOpen(false); }}
              style={{
                ...S.navItem,
                color: theme.textSecondary,
              }}
              onMouseEnter={(e) => e.currentTarget.style.background = theme.hoverBg}
              onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}
            >
              <Home size={18} />
              Back to Chat
            </div>
          </div>
        </aside>

        {/* Main Content */}
        <main style={S.main}>
          <div style={S.header}>
            <h1 style={S.title}>
              {currentPage === 'dashboard' && 'Dashboard'}
              {currentPage === 'users' && 'User Management'}
              {currentPage === 'packages' && 'Manage Packages'}
              {currentPage === 'payments' && 'Payment History'}
            </h1>
            <div style={S.headerButtons}>
              <button style={S.themeBtn} onClick={toggleTheme}>
                {darkMode ? '☀️ Light' : '🌙 Dark'}
              </button>
            </div>
          </div>

          {children}
        </main>
      </div>
    </>
  );
}
