'use client';

import * as React from 'react';

// Force dynamic rendering to avoid static generation issues with translations
export const dynamic = 'force-dynamic';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { cn } from '@/lib/utils';
import {
  LayoutDashboard,
  Users,
  BarChart3,
  MessageSquare,
  Settings,
  LogOut,
  Menu,
  X,
} from 'lucide-react';
import { useAuthStore } from '@/stores/auth.store';
import { useTranslation } from '@/hooks/use-translation';

/**
 * EN: Admin navigation items configuration
 * VI: Cấu hình các mục điều hướng Admin
 */
function getAdminNavItems(t: (key: string) => string) {
  return [
    {
      id: 'dashboard',
      label: t('admin.dashboard.title'),
      href: '/dashboard',
      icon: LayoutDashboard,
    },
    {
      id: 'users',
      label: t('admin.users.title'),
      href: '/dashboard/users',
      icon: Users,
    },
    {
      id: 'analytics',
      label: t('admin.analytics.title'),
      href: '/dashboard/analytics',
      icon: BarChart3,
    },
    {
      id: 'messages',
      label: t('admin.messages.title'),
      href: '/dashboard/messages',
      icon: MessageSquare,
    },
    {
      id: 'settings',
      label: t('admin.settings.title'),
      href: '/dashboard/settings',
      icon: Settings,
    },
  ];
}

/**
 * EN: Admin Dashboard layout component with sidebar navigation
 * VI: Component layout Admin Dashboard với điều hướng sidebar
 *
 * Features:
 * - Sidebar navigation with icons
 * - Responsive design (collapsible on mobile)
 * - User profile section
 * - Logout functionality
 * - Active route highlighting
 *
 * Tính năng:
 * - Điều hướng sidebar với icons
 * - Responsive design (có thể thu gọn trên mobile)
 * - Phần profile người dùng
 * - Chức năng logout
 * - Highlight route đang active
 */
export default function AdminDashboardLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const { t } = useTranslation();
  const pathname = usePathname();
  const { user, logout } = useAuthStore();
  const [sidebarOpen, setSidebarOpen] = React.useState(false);
  
  // EN: Get navigation items with translations / VI: Lấy các mục điều hướng với translations
  const adminNavItems = getAdminNavItems(t);

  /**
   * EN: Handle logout
   * VI: Xử lý logout
   */
  const handleLogout = async () => {
    await logout();
    window.location.href = '/login';
  };

  return (
    <div className="flex h-screen w-full overflow-hidden bg-bg-primary">
      {/* EN: Mobile sidebar overlay / VI: Overlay sidebar mobile */}
      {sidebarOpen && (
        <div
          className="fixed inset-0 bg-black/50 z-40 md:hidden"
          onClick={() => setSidebarOpen(false)}
          aria-hidden="true"
        />
      )}

      {/* EN: Sidebar / VI: Sidebar */}
      <aside
        className={cn(
          // EN: Base sidebar styles / VI: Style sidebar cơ bản
          'flex flex-col bg-bg-secondary border-r border-border-primary transition-all duration-[250ms] ease-out',
          // EN: Desktop: Fixed width / VI: Desktop: Chiều rộng cố định
          'w-64 flex-shrink-0',
          // EN: Mobile: Fixed position, slide in/out / VI: Mobile: Vị trí cố định, trượt vào/ra
          'max-md:fixed max-md:inset-y-0 max-md:left-0 max-md:z-50',
          'max-md:transform max-md:transition-transform',
          sidebarOpen ? 'max-md:translate-x-0' : 'max-md:-translate-x-full'
        )}
        aria-label={t('common.adminSidebar')}
      >
        {/* EN: Sidebar header with mobile menu button / VI: Header sidebar với nút menu mobile */}
        <div className="flex items-center justify-between p-4 border-b border-border-primary">
          <h1 className="text-xl font-semibold text-text-primary">
            GoodGo {t('common.admin')}
          </h1>
          <button
            onClick={() => setSidebarOpen(false)}
            className="md:hidden p-2 rounded-md hover:bg-bg-tertiary transition-colors"
            aria-label={t('common.closeSidebar')}
          >
            <X className="h-5 w-5 text-text-secondary" />
          </button>
        </div>

        {/* EN: Navigation menu / VI: Menu điều hướng */}
        <nav className="flex-1 overflow-y-auto p-4 space-y-1">
          {adminNavItems.map((item) => {
            const Icon = item.icon;
            const isActive = pathname === item.href || pathname.startsWith(item.href + '/');

            return (
              <Link
                key={item.id}
                href={item.href}
                onClick={() => setSidebarOpen(false)}
                className={cn(
                  // EN: Base nav item styles / VI: Style nav item cơ bản
                  'flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-[150ms]',
                  // EN: Active state / VI: Trạng thái active
                  isActive
                    ? 'bg-accent-primary text-white shadow-md'
                    : 'text-text-secondary hover:bg-bg-tertiary hover:text-text-primary',
                )}
                aria-current={isActive ? 'page' : undefined}
              >
                <Icon
                  className={cn(
                    'h-5 w-5 flex-shrink-0',
                    isActive ? 'text-white' : 'text-text-tertiary',
                  )}
                  aria-hidden="true"
                />
                <span>{item.label}</span>
              </Link>
            );
          })}
        </nav>

        {/* EN: User profile section / VI: Phần profile người dùng */}
        {user && (
          <div className="p-4 border-t border-border-primary">
            <div className="flex items-center gap-3 mb-3">
              <div className="h-10 w-10 rounded-full bg-chat-ai-bubble flex items-center justify-center">
                <span className="text-sm font-medium text-text-primary">
                  {user.email?.charAt(0).toUpperCase() || 'A'}
                </span>
              </div>
              <div className="flex-1 min-w-0">
                <p className="text-sm font-medium text-text-primary truncate">
                  {user.email}
                </p>
                <p className="text-xs text-text-tertiary truncate">
                  {user.role || t('common.admin')}
                </p>
              </div>
            </div>
            <button
              onClick={handleLogout}
              className="w-full flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium text-text-secondary hover:bg-bg-tertiary hover:text-text-primary transition-all duration-[150ms]"
              aria-label={t('common.logout')}
            >
              <LogOut className="h-5 w-5 flex-shrink-0" aria-hidden="true" />
              <span>{t('common.logout')}</span>
            </button>
          </div>
        )}
      </aside>

      {/* EN: Main content area / VI: Khu vực nội dung chính */}
      <main className="flex-1 overflow-y-auto">
        {/* EN: Mobile header with menu button / VI: Header mobile với nút menu */}
        <header className="sticky top-0 z-30 flex items-center justify-between p-4 bg-bg-secondary border-b border-border-primary md:hidden">
          <button
            onClick={() => setSidebarOpen(true)}
            className="p-2 rounded-md hover:bg-bg-tertiary transition-colors"
            aria-label={t('common.openSidebar')}
          >
            <Menu className="h-5 w-5 text-text-secondary" />
          </button>
          <h1 className="text-lg font-semibold text-text-primary">
            GoodGo {t('common.admin')}
          </h1>
          <div className="w-9" /> {/* EN: Spacer for centering / VI: Khoảng trống để căn giữa */}
        </header>

        {/* EN: Page content / VI: Nội dung trang */}
        <div className="p-6">{children}</div>
      </main>
    </div>
  );
}
