import { useState, useMemo } from 'react';
import { useNavigate, useLocation, useSearchParams, Outlet } from 'react-router-dom';
import { ConfigProvider, Layout, Typography, theme, Drawer, Divider, Alert, Tag } from 'antd';
import {
  LogoutOutlined,
  UserOutlined,
  GlobalOutlined,
  AppstoreOutlined,
  HomeOutlined,
  EnvironmentOutlined,
  ScheduleOutlined,
  HistoryOutlined,
  NodeIndexOutlined,
  CalendarOutlined,
  TagOutlined,
  TeamOutlined,
  MessageOutlined,
  BarChartOutlined,
} from '@ant-design/icons';
import { useAuthStore } from '@/stores/auth.store';
import { useSettingsStore } from '@/stores/settings.store';
import VolunteerFooterNav from '@/components/VolunteerFooterNav';
import PublicNavBar from '@/components/PublicNavBar';
import { useSSE } from '@/hooks/useSSE';
import { useLocalStorage } from '@/hooks/useLocalStorage';
import { isAdmin as checkIsAdmin } from '@/utils/roles';

const { Content, Footer } = Layout;

export default function VolunteerLayout() {
  const navigate = useNavigate();
  const location = useLocation();
  const [searchParams] = useSearchParams();
  // ?layout=embedded hides the top nav chrome (PublicNavBar) so the volunteer
  // surface feels like a continuation of whatever embedded/opener context the
  // user arrived from — currently the JSN /account → SSO redirect flow. The
  // footer nav stays (it's the in-cmlite navigation surface).
  const isEmbedded = searchParams.get('layout') === 'embedded';
  const { user, logout } = useAuthStore();
  const { settings } = useSettingsStore();
  const [menuOpen, setMenuOpen] = useState(false);
  const [welcomeDismissed, setWelcomeDismissed] = useLocalStorage('volunteer_welcome_dismissed', false);

  // Initialize SSE connection for real-time notifications + online presence
  useSSE();

  const isAdmin = user ? checkIsAdmin(user) : false;
  const colorBgBase = settings?.publicColorBgBase ?? '#0d1b2a';
  const colorBgContainer = settings?.publicColorBgContainer ?? '#1b2838';

  const handleLogout = async () => {
    await logout();
    navigate('/login', { replace: true });
  };

  // Build nav items list (mirrors VolunteerFooterNav logic)
  const navItems = useMemo(() => {
    const items: { key: string; icon: React.ReactNode; label: string }[] = [
      { key: '/volunteer', icon: <HomeOutlined />, label: 'Home' },
      { key: '/volunteer/map', icon: <EnvironmentOutlined />, label: 'Map' },
      { key: '/volunteer/shifts', icon: <ScheduleOutlined />, label: 'Shifts' },
      { key: '/volunteer/activity', icon: <HistoryOutlined />, label: 'Activity' },
      { key: '/volunteer/routes', icon: <NodeIndexOutlined />, label: 'Routes' },
    ];
    if (settings?.enableSocialCalendar) {
      items.push({ key: '/volunteer/calendar', icon: <CalendarOutlined />, label: 'Calendar' });
    }
    if (settings?.enableTicketedEvents) {
      items.push({ key: '/volunteer/tickets', icon: <TagOutlined />, label: 'Tickets' });
    }
    if (settings?.enableSocial) {
      items.push({ key: '/volunteer/feed', icon: <TeamOutlined />, label: 'Social' });
    }
    if (settings?.enableChat) {
      items.push({ key: '/volunteer/chat', icon: <MessageOutlined />, label: 'Chat' });
    }
    if (settings?.enableAnalytics) {
      items.push({ key: '/volunteer/my-analytics', icon: <BarChartOutlined />, label: 'My Stats' });
    }
    return items;
  }, [settings?.enableSocialCalendar, settings?.enableTicketedEvents, settings?.enableSocial, settings?.enableChat]);

  const activeKey = (() => {
    const path = location.pathname;
    if (path === '/volunteer') return '/volunteer';
    for (const item of navItems) {
      if (item.key !== '/volunteer' && path.startsWith(item.key)) return item.key;
    }
    return '/volunteer';
  })();

  return (
    <ConfigProvider
      theme={{
        algorithm: theme.darkAlgorithm,
        token: {
          colorPrimary: settings?.publicColorPrimary ?? '#3498db',
          colorBgBase: settings?.publicColorBgBase ?? '#0d1b2a',
          colorBgContainer: settings?.publicColorBgContainer ?? '#1b2838',
          colorBgElevated: settings?.publicColorBgContainer ?? '#1b2838',
          colorBorder: 'rgba(255,255,255,0.1)',
          colorBorderSecondary: 'rgba(255,255,255,0.06)',
          borderRadius: 8,
        },
      }}
    >
      <Layout style={{ minHeight: '100dvh', background: settings?.publicColorBgBase ?? '#0d1b2a' }}>
        {!isEmbedded && <PublicNavBar />}

        <Content
          style={{
            maxWidth: location.pathname === '/volunteer' ? 1280 : 800,
            width: '100%',
            margin: '0 auto',
            padding: '16px 12px max(60px, calc(44px + 16px + env(safe-area-inset-bottom))) 12px',
          }}
        >
          {!welcomeDismissed && (
            <Alert
              message="Welcome to the Volunteer Portal!"
              description="Here you can view your shifts, canvass your area, track your activity, and connect with your team."
              type="info"
              closable
              onClose={() => setWelcomeDismissed(true)}
              style={{ marginBottom: 16 }}
            />
          )}
          <Outlet />
        </Content>

        <Footer
          style={{
            position: 'fixed',
            bottom: 0,
            left: 0,
            right: 0,
            padding: 0,
            zIndex: 100,
          }}
        >
          <VolunteerFooterNav
            onMenuOpen={() => setMenuOpen(true)}
            menuActive={menuOpen}
          />
        </Footer>
      </Layout>

      {/* Navigation Menu Drawer */}
      <Drawer
        title={null}
        placement="left"
        onClose={() => setMenuOpen(false)}
        open={menuOpen}
        width={280}
        styles={{
          header: { display: 'none' },
          body: { background: colorBgBase, padding: 0 },
        }}
      >
        {/* User profile section */}
        <div style={{
          padding: '20px 20px 16px',
          background: colorBgContainer,
          borderBottom: '1px solid rgba(255,255,255,0.1)',
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <div style={{
              width: 40,
              height: 40,
              borderRadius: '50%',
              background: 'rgba(52,152,219,0.2)',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
            }}>
              <UserOutlined style={{ fontSize: 18, color: 'rgba(255,255,255,0.85)' }} />
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <Typography.Text strong style={{ color: '#fff', display: 'block', fontSize: 14 }}>
                {user?.name || 'Volunteer'}
              </Typography.Text>
              <Typography.Text style={{ color: 'rgba(255,255,255,0.45)', display: 'block', fontSize: 12 }}>
                {user?.email}
              </Typography.Text>
            </div>
          </div>
          <Tag color="blue" style={{ marginTop: 8, fontSize: 11 }}>
            {user?.role === 'USER' ? 'Volunteer' : user?.role?.replace('_', ' ') ?? 'Volunteer'}
          </Tag>
        </div>

        {/* Navigation items */}
        <div style={{ padding: '8px 0' }}>
          {navItems.map(({ key, icon, label }) => {
            const isActive = activeKey === key;
            return (
              <div
                key={key}
                onClick={() => { navigate(key); setMenuOpen(false); }}
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  gap: 12,
                  padding: '12px 20px',
                  cursor: 'pointer',
                  color: isActive ? '#fff' : 'rgba(255,255,255,0.7)',
                  fontWeight: isActive ? 600 : 400,
                  fontSize: 14,
                  background: isActive ? 'rgba(52,152,219,0.15)' : 'transparent',
                  borderRight: isActive ? '3px solid #3498db' : '3px solid transparent',
                  transition: 'all 0.2s',
                }}
              >
                {icon}
                <span>{label}</span>
              </div>
            );
          })}
        </div>

        <Divider style={{ margin: '4px 20px', borderColor: 'rgba(255,255,255,0.1)' }} />

        {/* Cross-navigation links */}
        <div style={{ padding: '4px 0' }}>
          <div
            onClick={() => { navigate('/home'); setMenuOpen(false); }}
            style={{
              display: 'flex',
              alignItems: 'center',
              gap: 12,
              padding: '12px 20px',
              cursor: 'pointer',
              color: 'rgba(255,255,255,0.7)',
              fontSize: 14,
            }}
          >
            <GlobalOutlined />
            <span>Public Website</span>
          </div>
          {isAdmin && (
            <div
              onClick={() => { navigate('/app'); setMenuOpen(false); }}
              style={{
                display: 'flex',
                alignItems: 'center',
                gap: 12,
                padding: '12px 20px',
                cursor: 'pointer',
                color: 'rgba(255,255,255,0.7)',
                fontSize: 14,
              }}
            >
              <AppstoreOutlined />
              <span>Admin Panel</span>
            </div>
          )}
        </div>

        <Divider style={{ margin: '4px 20px', borderColor: 'rgba(255,255,255,0.1)' }} />

        {/* Logout */}
        <div style={{ padding: '4px 0' }}>
          <div
            onClick={() => { handleLogout(); setMenuOpen(false); }}
            style={{
              display: 'flex',
              alignItems: 'center',
              gap: 12,
              padding: '12px 20px',
              cursor: 'pointer',
              color: 'rgba(255,255,255,0.7)',
              fontSize: 14,
            }}
          >
            <LogoutOutlined />
            <span>Logout</span>
          </div>
        </div>
      </Drawer>
    </ConfigProvider>
  );
}
