import { useState, useEffect, useMemo } from 'react';
import { Link, useLocation, useNavigate } from 'react-router-dom';
import { Typography, Space, Grid, Drawer, Dropdown, Button, Tooltip, message } from 'antd';
import {
  MenuOutlined,
  CloseOutlined,
  LoginOutlined,
  LogoutOutlined,
  AppstoreOutlined,
  TeamOutlined,
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  EllipsisOutlined,
  SearchOutlined,
  UserOutlined,
  DownOutlined,
  UpOutlined,
} from '@ant-design/icons';
import { useSettingsStore } from '@/stores/settings.store';
import { useAuthStore } from '@/stores/auth.store';
import { useLocalStorage } from '@/hooks/useLocalStorage';
import PublicSearchModal from '@/components/PublicSearchModal';
import NotificationBell from '@/components/social/NotificationBell';
import { api } from '@/lib/api';
import { resolveNavUrl } from '@/lib/service-url';
import {
  DEFAULT_NAV_ITEMS,
  ICON_MAP,
  mergeNavDefaults,
  filterNavItems,
  buildFeatureFlags,
  isItemActive,
} from '@/lib/nav-defaults';
import type { NavItem } from '@/types/api';
import { isAdmin as checkIsAdmin } from '@/utils/roles';

const navItemStyle: React.CSSProperties = {
  color: 'rgba(255, 255, 255, 0.85)',
  textDecoration: 'none',
  display: 'flex',
  alignItems: 'center',
  gap: 6,
  fontSize: 14,
  transition: 'color 0.2s',
  whiteSpace: 'nowrap',
  cursor: 'pointer',
  background: 'none',
  border: 'none',
  padding: 0,
  font: 'inherit',
};

/** Resolve external URLs for builtin items (including $token paths) */
function resolveItemUrl(item: NavItem): string {
  if (item.path.startsWith('$')) return resolveNavUrl(item.path);
  if (item.external && item.path.startsWith('http')) return item.path;
  return item.path;
}

interface PublicNavBarProps {
  activePath?: string;
  showAuth?: boolean;
  onSignInClick?: () => void;
}

export default function PublicNavBar({ activePath, showAuth = true, onSignInClick }: PublicNavBarProps) {
  const { settings } = useSettingsStore();
  const { isAuthenticated, logout, user } = useAuthStore();
  const isAdmin = isAuthenticated && user ? checkIsAdmin(user) : false;
  const location = useLocation();
  const navigate = useNavigate();
  const [drawerOpen, setDrawerOpen] = useState(false);
  const [searchOpen, setSearchOpen] = useState(false);
  const [navCollapsed, setNavCollapsed] = useLocalStorage('public_nav_collapsed', false);
  const [profileLoading, setProfileLoading] = useState(false);
  const [expandedGroups, setExpandedGroups] = useState<Set<string>>(new Set());
  const handleSignIn = onSignInClick ?? (() => navigate('/login'));

  const handleMyProfile = async () => {
    if (profileLoading) return;
    setProfileLoading(true);
    try {
      const { data } = await api.get<{ token: string }>('/auth/me/profile-token');
      navigate(`/profile/${data.token}`);
    } catch {
      message.error('Unable to load profile');
    } finally {
      setProfileLoading(false);
    }
  };
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;

  // Global Ctrl+K / Cmd+K to open search
  useEffect(() => {
    const handler = (e: KeyboardEvent) => {
      if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
        e.preventDefault();
        setSearchOpen(true);
      }
    };
    window.addEventListener('keydown', handler);
    return () => window.removeEventListener('keydown', handler);
  }, []);

  /** Animated label that collapses to zero-width when navCollapsed is true */
  const NavLabel = ({ label }: { label: string }) => (
    <span style={{
      display: 'inline-block',
      maxWidth: navCollapsed ? 0 : 200,
      opacity: navCollapsed ? 0 : 1,
      overflow: 'hidden',
      transition: 'max-width 0.25s ease, opacity 0.2s ease',
      whiteSpace: 'nowrap',
    }}>
      {label}
    </span>
  );

  const headerGradient = settings?.publicHeaderGradient ?? 'linear-gradient(135deg, #005a9c 0%, #007acc 100%)';
  const orgName = settings?.organizationName ?? 'Changemaker Lite';
  const logoUrl = settings?.organizationLogoUrl;
  const colorBgBase = settings?.publicColorBgBase ?? '#0d1b2a';
  const colorBgContainer = settings?.publicColorBgContainer ?? '#1b2838';

  // Determine active route for nav highlight
  const currentActive = activePath ?? location.pathname;

  const featureFlags = useMemo(() => buildFeatureFlags(settings), [settings]);

  // Get filtered, sorted nav items (with group support)
  const navItems = useMemo(() => {
    const merged = mergeNavDefaults(settings?.navConfig?.items ?? DEFAULT_NAV_ITEMS);
    return filterNavItems(merged, featureFlags);
  }, [settings?.navConfig, featureFlags]);

  // Desktop overflow: group items beyond MAX_VISIBLE into "More" dropdown
  const MAX_VISIBLE_NAV = 7;
  const visibleNavItems = navCollapsed ? navItems : navItems.slice(0, MAX_VISIBLE_NAV);
  const overflowNavItems = navCollapsed ? [] : navItems.slice(MAX_VISIBLE_NAV);

  const toggleGroup = (groupId: string) => {
    setExpandedGroups(prev => {
      const next = new Set(prev);
      if (next.has(groupId)) next.delete(groupId);
      else next.add(groupId);
      return next;
    });
  };

  const renderDesktopLink = (item: NavItem) => {
    const isActive = isItemActive(item, currentActive);
    const icon = ICON_MAP[item.icon] ?? null;
    const linkStyle: React.CSSProperties = {
      ...navItemStyle,
      gap: navCollapsed ? 0 : 6,
      color: isActive ? '#fff' : 'rgba(255, 255, 255, 0.85)',
      fontWeight: isActive ? 600 : undefined,
      borderBottom: isActive ? '2px solid #fff' : '2px solid transparent',
      paddingBottom: 2,
    };

    // Group item: render as Dropdown trigger
    if (item.type === 'group' && item.children) {
      const menuItems = item.children.map(child => ({
        key: child.id,
        icon: ICON_MAP[child.icon],
        label: child.external ? (
          <a href={resolveItemUrl(child)} target="_blank" rel="noopener noreferrer" style={{ color: 'inherit' }}>{child.label}</a>
        ) : child.label,
        onClick: child.external ? undefined : () => navigate(child.path),
      }));

      return (
        <Dropdown
          key={item.id}
          menu={{ items: menuItems }}
          placement="bottomRight"
        >
          <Tooltip title={navCollapsed ? item.label : ''}>
            <span
              style={linkStyle}
              onMouseEnter={(e) => { e.currentTarget.style.color = '#fff'; }}
              onMouseLeave={(e) => { if (!isActive) e.currentTarget.style.color = 'rgba(255, 255, 255, 0.85)'; }}
            >
              {icon}
              <NavLabel label={item.label} />
              {!navCollapsed && <DownOutlined style={{ fontSize: 10, marginLeft: -2 }} />}
            </span>
          </Tooltip>
        </Dropdown>
      );
    }

    if (item.external) {
      return (
        <Tooltip key={item.id} title={navCollapsed ? item.label : ''}>
          <a
            href={resolveItemUrl(item)}
            target="_blank"
            rel="noopener noreferrer"
            style={linkStyle}
            onMouseEnter={(e) => { e.currentTarget.style.color = '#fff'; }}
            onMouseLeave={(e) => { if (!isActive) e.currentTarget.style.color = 'rgba(255, 255, 255, 0.85)'; }}
          >
            {icon}
            <NavLabel label={item.label} />
          </a>
        </Tooltip>
      );
    }

    return (
      <Tooltip key={item.id} title={navCollapsed ? item.label : ''}>
        <Link
          to={item.path}
          style={linkStyle}
          onMouseEnter={(e) => { e.currentTarget.style.color = '#fff'; }}
          onMouseLeave={(e) => { if (!isActive) e.currentTarget.style.color = 'rgba(255, 255, 255, 0.85)'; }}
        >
          {icon}
          <NavLabel label={item.label} />
        </Link>
      </Tooltip>
    );
  };

  const renderMobileLink = (item: NavItem, indent = false) => {
    const isActive = isItemActive(item, currentActive);
    const icon = ICON_MAP[item.icon] ?? null;
    const style: React.CSSProperties = {
      display: 'flex',
      alignItems: 'center',
      gap: 10,
      padding: indent ? '10px 24px 10px 44px' : '12px 24px',
      color: isActive ? '#fff' : 'rgba(255,255,255,0.85)',
      textDecoration: 'none',
      fontSize: indent ? 14 : 15,
      fontWeight: isActive ? 600 : 400,
      background: isActive ? 'rgba(255,255,255,0.1)' : 'transparent',
      borderRadius: 4,
    };

    if (item.external) {
      return (
        <a
          key={item.id}
          href={resolveItemUrl(item)}
          target="_blank"
          rel="noopener noreferrer"
          onClick={() => setDrawerOpen(false)}
          style={style}
        >
          {icon}
          <span>{item.label}</span>
        </a>
      );
    }

    return (
      <Link
        key={item.id}
        to={item.path}
        onClick={() => setDrawerOpen(false)}
        style={style}
      >
        {icon}
        <span>{item.label}</span>
      </Link>
    );
  };

  const renderMobileGroup = (item: NavItem) => {
    const isActive = isItemActive(item, currentActive);
    const icon = ICON_MAP[item.icon] ?? null;
    const expanded = expandedGroups.has(item.id);

    return (
      <div key={item.id}>
        <span
          role="button"
          tabIndex={0}
          onClick={() => toggleGroup(item.id)}
          onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); toggleGroup(item.id); } }}
          style={{
            display: 'flex',
            alignItems: 'center',
            gap: 10,
            padding: '12px 24px',
            color: isActive ? '#fff' : 'rgba(255,255,255,0.85)',
            fontSize: 15,
            fontWeight: isActive ? 600 : 400,
            cursor: 'pointer',
            background: 'none',
            border: 'none',
            font: 'inherit',
            width: '100%',
            textAlign: 'left',
          }}
        >
          {icon}
          <span style={{ flex: 1 }}>{item.label}</span>
          {expanded ? <UpOutlined style={{ fontSize: 10 }} /> : <DownOutlined style={{ fontSize: 10 }} />}
        </span>
        {expanded && item.children?.map(child => renderMobileLink(child, true))}
      </div>
    );
  };

  // Build overflow menu items with group support (nested children)
  const overflowMenuItems = overflowNavItems.map(item => {
    if (item.type === 'group' && item.children) {
      return {
        key: item.id,
        icon: ICON_MAP[item.icon],
        label: item.label,
        children: item.children.map(child => ({
          key: child.id,
          icon: ICON_MAP[child.icon],
          label: child.external ? (
            <a href={resolveItemUrl(child)} target="_blank" rel="noopener noreferrer" style={{ color: 'inherit' }}>{child.label}</a>
          ) : child.label,
          onClick: child.external ? undefined : () => navigate(child.path),
        })),
      };
    }
    return {
      key: item.id,
      icon: ICON_MAP[item.icon],
      label: item.external ? (
        <a href={resolveItemUrl(item)} target="_blank" rel="noopener noreferrer" style={{ color: 'inherit' }}>{item.label}</a>
      ) : item.label,
      onClick: item.external ? undefined : () => navigate(item.path),
    };
  });

  return (
    <>
      <div
        style={{
          background: headerGradient,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          padding: '0 24px',
          height: 56,
          overflow: 'hidden',
          flexShrink: 0,
        }}
      >
        {/* Left: Logo + Brand */}
        <Link to="/home" style={{ textDecoration: 'none', display: 'flex', alignItems: 'center', gap: 10 }}>
          {logoUrl && (
            <img
              src={logoUrl}
              alt={orgName}
              style={{ maxHeight: 32, objectFit: 'contain' }}
            />
          )}
          <Typography.Text strong style={{ fontSize: 18, color: '#fff' }}>
            {orgName}
          </Typography.Text>
        </Link>

        {/* Right: Navigation */}
        {isMobile ? (
          <Space size={4}>
            {isAuthenticated && settings?.enableSocial && <NotificationBell />}
            <Button
              type="text"
              icon={<MenuOutlined style={{ color: '#fff', fontSize: 20 }} />}
              onClick={() => setDrawerOpen(true)}
              aria-label="Open navigation menu"
              style={{ padding: '4px 8px' }}
            />
          </Space>
        ) : (
          <Space size={navCollapsed ? 8 : 16} style={{ flexWrap: 'nowrap', overflow: 'hidden' }}>
            {visibleNavItems.map(renderDesktopLink)}
            {overflowMenuItems.length > 0 && (
              <Dropdown
                menu={{ items: overflowMenuItems }}
                placement="bottomRight"
              >
                <span
                  style={{ ...navItemStyle, cursor: 'pointer' }}
                  onMouseEnter={(e) => { e.currentTarget.style.color = '#fff'; }}
                  onMouseLeave={(e) => { e.currentTarget.style.color = 'rgba(255, 255, 255, 0.85)'; }}
                >
                  <EllipsisOutlined />
                  <NavLabel label="More" />
                </span>
              </Dropdown>
            )}

            {/* Search button */}
            <Tooltip title={navCollapsed ? 'Search (Ctrl+K)' : 'Search'}>
              <span
                role="button"
                tabIndex={0}
                onClick={() => setSearchOpen(true)}
                onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); setSearchOpen(true); } }}
                style={{ ...navItemStyle, gap: navCollapsed ? 0 : 6 }}
                onMouseEnter={(e) => { e.currentTarget.style.color = '#fff'; }}
                onMouseLeave={(e) => { e.currentTarget.style.color = 'rgba(255, 255, 255, 0.85)'; }}
              >
                <SearchOutlined />
                <NavLabel label="Search" />
              </span>
            </Tooltip>

            {/* Collapse toggle */}
            <Tooltip title={navCollapsed ? 'Expand navigation' : 'Collapse navigation'}>
              <span
                role="button"
                tabIndex={0}
                onClick={() => setNavCollapsed(!navCollapsed)}
                onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); setNavCollapsed(!navCollapsed); } }}
                style={{
                  ...navItemStyle,
                  color: 'rgba(255, 255, 255, 0.5)',
                  borderLeft: '1px solid rgba(255, 255, 255, 0.2)',
                  paddingLeft: 12,
                  marginLeft: 4,
                }}
                onMouseEnter={(e) => { e.currentTarget.style.color = '#fff'; }}
                onMouseLeave={(e) => { e.currentTarget.style.color = 'rgba(255, 255, 255, 0.5)'; }}
              >
                {navCollapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
              </span>
            </Tooltip>

            {/* Notification bell (authenticated + social enabled) */}
            {isAuthenticated && settings?.enableSocial && <NotificationBell />}

            {/* Auth: user dropdown when logged in, Sign In when not */}
            {isAuthenticated ? (
              <Dropdown
                menu={{
                  items: [
                    ...(isAdmin ? [{
                      key: 'admin',
                      icon: <AppstoreOutlined />,
                      label: 'Admin Panel',
                      onClick: () => navigate('/app'),
                      style: { fontWeight: 600 },
                    }] : []),
                    {
                      key: 'volunteer',
                      icon: <TeamOutlined />,
                      label: 'Volunteer Portal',
                      onClick: () => navigate('/volunteer'),
                      style: isAdmin ? undefined : { fontWeight: 600 },
                    },
                    { type: 'divider' as const },
                    {
                      key: 'profile',
                      icon: <UserOutlined />,
                      label: 'My Profile',
                      disabled: profileLoading,
                      onClick: handleMyProfile,
                    },
                    { type: 'divider' as const },
                    {
                      key: 'logout',
                      icon: <LogoutOutlined />,
                      label: 'Logout',
                      onClick: () => logout(),
                    },
                  ],
                }}
                placement="bottomRight"
                trigger={['click']}
              >
                <span
                  style={{
                    ...navItemStyle,
                    gap: 6,
                    cursor: 'pointer',
                    borderLeft: '1px solid rgba(255,255,255,0.2)',
                    paddingLeft: 12,
                    marginLeft: 4,
                  }}
                  onMouseEnter={(e) => { e.currentTarget.style.color = '#fff'; }}
                  onMouseLeave={(e) => { e.currentTarget.style.color = 'rgba(255, 255, 255, 0.85)'; }}
                >
                  <UserOutlined />
                  <span style={{
                    maxWidth: navCollapsed ? 0 : 120,
                    opacity: navCollapsed ? 0 : 1,
                    overflow: 'hidden',
                    transition: 'max-width 0.25s ease, opacity 0.2s ease',
                    whiteSpace: 'nowrap',
                    textOverflow: 'ellipsis',
                  }}>
                    {user?.name || user?.email || 'Account'}
                  </span>
                </span>
              </Dropdown>
            ) : showAuth && (
              <Tooltip title={navCollapsed ? 'Sign In' : ''}>
                <span
                  role="button"
                  tabIndex={0}
                  onClick={handleSignIn}
                  onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); handleSignIn(); } }}
                  style={{ ...navItemStyle, gap: navCollapsed ? 0 : 6 }}
                  onMouseEnter={(e) => { e.currentTarget.style.color = '#fff'; }}
                  onMouseLeave={(e) => { e.currentTarget.style.color = 'rgba(255, 255, 255, 0.85)'; }}
                >
                  <LoginOutlined /><NavLabel label="Sign In" />
                </span>
              </Tooltip>
            )}
          </Space>
        )}
      </div>

      {/* Mobile Navigation Drawer */}
      <Drawer
        title={orgName}
        placement="right"
        onClose={() => setDrawerOpen(false)}
        open={drawerOpen}
        width={280}
        closeIcon={<CloseOutlined style={{ color: 'rgba(255,255,255,0.85)' }} />}
        styles={{
          header: { background: colorBgContainer, borderBottom: '1px solid rgba(255,255,255,0.1)' },
          body: { background: colorBgBase, padding: '16px 0' },
        }}
      >
        <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
          {/* Highlighted portal/admin link at top when authenticated */}
          {isAuthenticated && (
            <>
              <Link
                to={isAdmin ? '/app' : '/volunteer'}
                onClick={() => setDrawerOpen(false)}
                style={{
                  display: 'flex', alignItems: 'center', gap: 10,
                  padding: '12px 24px',
                  color: '#fff',
                  textDecoration: 'none', fontSize: 15,
                  fontWeight: 600,
                  borderRadius: 4,
                  margin: '0 8px 4px',
                  background: 'rgba(52,152,219,0.15)',
                }}
              >
                {isAdmin ? <AppstoreOutlined /> : <TeamOutlined />}
                <span>{isAdmin ? 'Open Admin Panel' : 'Open Volunteer Portal'}</span>
              </Link>
            </>
          )}
          {navItems.map(item =>
            item.type === 'group' && item.children
              ? renderMobileGroup(item)
              : renderMobileLink(item)
          )}
          <div style={{ borderTop: '1px solid rgba(255,255,255,0.1)', margin: '8px 24px' }} />
          {isAuthenticated ? (
            <>
              <Link
                to="/volunteer"
                onClick={() => setDrawerOpen(false)}
                style={{
                  display: 'flex', alignItems: 'center', gap: 10,
                  padding: '12px 24px',
                  color: 'rgba(255,255,255,0.85)',
                  textDecoration: 'none', fontSize: 15,
                  borderRadius: 4,
                }}
              >
                <TeamOutlined /> <span>Volunteer Portal</span>
              </Link>
              <span
                role="button"
                tabIndex={0}
                onClick={() => { handleMyProfile(); setDrawerOpen(false); }}
                onKeyDown={(e) => { if (e.key === 'Enter') { handleMyProfile(); setDrawerOpen(false); } }}
                style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '12px 24px', color: 'rgba(255,255,255,0.85)', cursor: 'pointer', fontSize: 15, background: 'none', border: 'none', font: 'inherit', opacity: profileLoading ? 0.5 : 1 }}
              >
                <UserOutlined /> <span>My Profile</span>
              </span>
              <span
                role="button"
                tabIndex={0}
                onClick={() => { logout(); setDrawerOpen(false); }}
                onKeyDown={(e) => { if (e.key === 'Enter') { logout(); setDrawerOpen(false); } }}
                style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '12px 24px', color: 'rgba(255,255,255,0.85)', cursor: 'pointer', fontSize: 15, background: 'none', border: 'none', font: 'inherit' }}
              >
                <LogoutOutlined /> <span>Logout</span>
              </span>
            </>
          ) : showAuth && (
            <span
              role="button"
              tabIndex={0}
              onClick={() => { handleSignIn(); setDrawerOpen(false); }}
              onKeyDown={(e) => { if (e.key === 'Enter') { handleSignIn(); setDrawerOpen(false); } }}
              style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '12px 24px', color: 'rgba(255,255,255,0.85)', cursor: 'pointer', fontSize: 15, background: 'none', border: 'none', font: 'inherit' }}
            >
              <LoginOutlined /> <span>Sign In</span>
            </span>
          )}
        </div>
      </Drawer>

      <PublicSearchModal open={searchOpen} onClose={() => setSearchOpen(false)} />
    </>
  );
}
