import { Avatar, DropdownMenu } from '@/components/ui';
import { useAuth } from '@/contexts/AuthContext';
import { useTranslation } from '@/hooks/useI18n';
import { clsx } from 'clsx';
import {
  BarChart3,
  Bell,
  Building2,
  ChevronRight,
  FileText,
  Languages,
  LayoutDashboard,
  LogOut,
  Menu,
  Settings,
  User,
  Users,
  X,
} from 'lucide-react';
import React, { useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';

export interface AdminNavItem {
  id: string;
  label: string;
  icon: React.ReactNode;
  path: string;
  badge?: number;
  children?: AdminNavItem[];
}

export interface AdminLayoutProps {
  children: React.ReactNode;
  title?: string;
  breadcrumbs?: Array<{ label: string; href?: string }>;
}

const defaultNavItems: AdminNavItem[] = [
  {
    id: 'dashboard',
    label: 'Dashboard',
    icon: <LayoutDashboard className="h-5 w-5" />,
    path: '/admin',
  },
  {
    id: 'organizations',
    label: 'Organizations',
    icon: <Building2 className="h-5 w-5" />,
    path: '/admin/organizations',
    children: [
      { id: 'org-list', label: 'All Organizations', path: '/admin/organizations' },
      { id: 'org-new', label: 'New Organization', path: '/admin/organizations/new' },
      { id: 'org-verify', label: 'Verification Queue', path: '/admin/organizations/verification' },
    ],
  },
  {
    id: 'localization',
    label: 'Localization',
    icon: <Languages className="h-5 w-5" />,
    path: '/admin/localization',
    children: [
      { id: 'loc-ui', label: 'UI Translations', path: '/admin/localization/ui' },
      { id: 'loc-data', label: 'Data Translations', path: '/admin/localization/data' },
    ],
  },
  {
    id: 'content',
    label: 'Content',
    icon: <FileText className="h-5 w-5" />,
    path: '/admin/content',
    children: [
      { id: 'content-pages', label: 'Static Pages', path: '/admin/content/pages' },
      { id: 'content-announcements', label: 'Announcements', path: '/admin/content/announcements' },
      { id: 'content-media', label: 'Media Library', path: '/admin/content/media' },
    ],
  },
  {
    id: 'users',
    label: 'Users',
    icon: <Users className="h-5 w-5" />,
    path: '/admin/users',
    children: [
      { id: 'users-list', label: 'All Users', path: '/admin/users' },
      { id: 'users-new', label: 'New User', path: '/admin/users/new' },
      { id: 'users-activity', label: 'Activity Log', path: '/admin/users/activity' },
    ],
  },
  {
    id: 'analytics',
    label: 'Analytics',
    icon: <BarChart3 className="h-5 w-5" />,
    path: '/admin/analytics',
    children: [
      { id: 'analytics-overview', label: 'Overview', path: '/admin/analytics' },
      { id: 'analytics-orgs', label: 'Organizations', path: '/admin/analytics/organizations' },
      { id: 'analytics-users', label: 'User Activity', path: '/admin/analytics/users' },
      { id: 'analytics-matching', label: 'Matching', path: '/admin/analytics/matching' },
    ],
  },
  {
    id: 'settings',
    label: 'Settings',
    icon: <Settings className="h-5 w-5" />,
    path: '/admin/settings',
    children: [
      { id: 'settings-general', label: 'General', path: '/admin/settings/general' },
      { id: 'settings-localization', label: 'Localization', path: '/admin/settings/localization' },
      { id: 'settings-integrations', label: 'Integrations', path: '/admin/settings/integrations' },
      { id: 'settings-email', label: 'Email Templates', path: '/admin/settings/email' },
      { id: 'settings-maintenance', label: 'Maintenance', path: '/admin/settings/maintenance' },
    ],
  },
];

/**
 * Admin Layout with sidebar navigation
 */
export const AdminLayout = ({ children, title, breadcrumbs }: AdminLayoutProps) => {
  const [sidebarOpen, setSidebarOpen] = useState(true);
  const [expandedItems, setExpandedItems] = useState<Set<string>>(new Set());
  const location = useLocation();
  const navigate = useNavigate();
  const { user, logout } = useAuth();
  const { t } = useTranslation();

  const toggleSidebar = () => setSidebarOpen(!sidebarOpen);
  const toggleExpanded = (id: string) => {
    setExpandedItems((prev) => {
      const newSet = new Set(prev);
      if (newSet.has(id)) {
        newSet.delete(id);
      } else {
        newSet.add(id);
      }
      return newSet;
    });
  };

  const isActive = (path: string) => location.pathname === path || location.pathname.startsWith(path + '/');

  const userMenuItems = [
    {
      label: 'Profile',
      value: 'profile',
      icon: <User className="h-4 w-4" />,
      onClick: () => navigate('/admin/profile'),
    },
    {
      label: 'Settings',
      value: 'settings',
      icon: <Settings className="h-4 w-4" />,
      onClick: () => navigate('/admin/settings'),
    },
    {
      label: 'divider',
      value: 'divider',
      divider: true,
    },
    {
      label: 'Logout',
      value: 'logout',
      icon: <LogOut className="h-4 w-4" />,
      onClick: () => logout(),
    },
  ];

  return (
    <div className="flex h-screen overflow-hidden bg-background">
      {/* Sidebar */}
      <aside
        className={clsx(
          'flex flex-col border-r bg-card transition-all duration-300',
          'z-40',
          {
            'w-64': sidebarOpen,
            'w-0 overflow-hidden': !sidebarOpen,
          }
        )}
      >
        {/* Sidebar Header */}
        <div className="flex h-16 items-center justify-between border-b px-4">
          {sidebarOpen && (
            <>
              <h1 className="text-lg font-semibold">Admin Panel</h1>
              <button
                onClick={toggleSidebar}
                className="rounded-md p-1 hover:bg-muted"
                aria-label="Close sidebar"
              >
                <X className="h-5 w-5" />
              </button>
            </>
          )}
        </div>

        {/* Navigation */}
        {sidebarOpen && (
          <nav className="flex-1 overflow-y-auto p-4">
            <ul className="space-y-1">
              {defaultNavItems.map((item) => {
                const hasChildren = item.children && item.children.length > 0;
                const isExpanded = expandedItems.has(item.id);
                const itemActive = isActive(item.path);

                return (
                  <li key={item.id}>
                    {hasChildren ? (
                      <>
                        <button
                          onClick={(e) => {
                            e.preventDefault();
                            toggleExpanded(item.id);
                          }}
                          className={clsx(
                            'w-full flex items-center justify-between gap-2 px-3 py-2 rounded-md text-sm font-medium transition-colors',
                            {
                              'bg-primary/10 text-primary': itemActive,
                              'text-muted-foreground hover:bg-muted hover:text-foreground': !itemActive,
                            }
                          )}
                        >
                          <div className="flex items-center gap-2">
                            {item.icon}
                            <span>{item.label}</span>
                          </div>
                          {item.badge && (
                            <span className="rounded-full bg-primary px-2 py-0.5 text-xs text-primary-foreground">
                              {item.badge}
                            </span>
                          )}
                          <ChevronRight
                            className={clsx('h-4 w-4 transition-transform', {
                              'rotate-90': isExpanded,
                            })}
                          />
                        </button>
                        {isExpanded && item.children && (
                          <ul className="ml-6 mt-1 space-y-1 border-l pl-4">
                            {item.children.map((child) => {
                              const childActive = isActive(child.path);
                              return (
                                <li key={child.id}>
                                  <button
                                    onClick={(e) => {
                                      e.preventDefault();
                                      navigate(child.path);
                                    }}
                                    className={clsx(
                                      'w-full text-left px-3 py-2 rounded-md text-sm transition-colors',
                                      {
                                        'bg-primary/10 text-primary font-medium': childActive,
                                        'text-muted-foreground hover:bg-muted hover:text-foreground': !childActive,
                                      }
                                    )}
                                  >
                                    {child.label}
                                  </button>
                                </li>
                              );
                            })}
                          </ul>
                        )}
                      </>
                    ) : (
                      <button
                        onClick={(e) => {
                          e.preventDefault();
                          navigate(item.path);
                        }}
                        className={clsx(
                          'w-full flex items-center gap-2 px-3 py-2 rounded-md text-sm font-medium transition-colors',
                          {
                            'bg-primary/10 text-primary': itemActive,
                            'text-muted-foreground hover:bg-muted hover:text-foreground': !itemActive,
                          }
                        )}
                      >
                        {item.icon}
                        <span>{item.label}</span>
                        {item.badge && (
                          <span className="ml-auto rounded-full bg-primary px-2 py-0.5 text-xs text-primary-foreground">
                            {item.badge}
                          </span>
                        )}
                      </button>
                    )}
                  </li>
                );
              })}
            </ul>
          </nav>
        )}
      </aside>

      {/* Main Content */}
      <div className="flex flex-1 flex-col overflow-hidden">
        {/* Header */}
        <header className="flex h-16 items-center justify-between border-b bg-background px-4">
          <div className="flex items-center gap-4">
            <button
              onClick={toggleSidebar}
              className="rounded-md p-1 hover:bg-muted"
              aria-label="Toggle sidebar"
            >
              <Menu className="h-5 w-5" />
            </button>
            {title && <h2 className="text-lg font-semibold">{title}</h2>}
          </div>

          <div className="flex items-center gap-4">
            <button className="relative rounded-md p-2 hover:bg-muted" aria-label="Notifications">
              <Bell className="h-5 w-5" />
              <span className="absolute top-1 right-1 h-2 w-2 rounded-full bg-destructive" />
            </button>

            <DropdownMenu
              trigger={
                <div className="flex items-center gap-2 cursor-pointer">
                  <Avatar src={undefined} name={user?.name || 'Admin'} size="sm" />
                  <span className="hidden md:block text-sm font-medium">{user?.name || 'Admin'}</span>
                </div>
              }
              items={userMenuItems}
              align="right"
            />
          </div>
        </header>

        {/* Page Content */}
        <main className="flex-1 overflow-y-auto bg-muted/30">
          <div className="container mx-auto p-6">
            {breadcrumbs && breadcrumbs.length > 0 && (
              <div className="mb-4">
                {/* Breadcrumbs will be rendered here if needed */}
              </div>
            )}
            {children}
          </div>
        </main>
      </div>
    </div>
  );
};

