import { useEffect, useState } from 'react';
import { ConfigProvider, Layout, theme, Grid } from 'antd';
import { Outlet } from 'react-router-dom';
import MediaSidebar from '@/components/media/MediaSidebar';
import MediaBottomNav from '@/components/media/MediaBottomNav';
import ChatNotificationToast from '@/components/media/ChatNotificationToast';
import { ChatBarProvider } from '@/components/media/chatbar/ChatBarContext';
import ChatBar from '@/components/media/chatbar/ChatBar';
import { useChatNotifications } from '@/hooks/useChatNotifications';
import { useSettingsStore } from '@/stores/settings.store';
import { hexToRgba } from '@/utils/color';
import PublicNavBar from '@/components/PublicNavBar';

const { useBreakpoint } = Grid;

export default function MediaPublicLayout() {
  const { settings } = useSettingsStore();
  const { notifications, clearNotification } = useChatNotifications();

  // Read colors from site settings (same source as PublicLayout)
  const colorPrimary = settings?.publicColorPrimary ?? '#3498db';
  const colorBgBase = settings?.publicColorBgBase ?? '#0d1b2a';
  const colorBgContainer = settings?.publicColorBgContainer ?? '#1b2838';
  const orgName = settings?.organizationName ?? 'Changemaker Lite';

  const screens = useBreakpoint();
  const isMobile = !screens.md; // < 768px

  // Get sidebar collapse state from localStorage
  const [sidebarCollapsed, setSidebarCollapsed] = useState(() => {
    const saved = localStorage.getItem('media_sidebar_collapsed');
    return saved ? JSON.parse(saved) : false;
  });

  // Listen for sidebar collapse state changes
  useEffect(() => {
    const handleStorage = () => {
      const saved = localStorage.getItem('media_sidebar_collapsed');
      if (saved) {
        setSidebarCollapsed(JSON.parse(saved));
      }
    };

    window.addEventListener('storage', handleStorage);
    // Also poll localStorage every 100ms to catch same-window changes
    const interval = setInterval(handleStorage, 100);

    return () => {
      window.removeEventListener('storage', handleStorage);
      clearInterval(interval);
    };
  }, []);

  // Set document title for media pages
  useEffect(() => {
    document.title = `Media Gallery | ${orgName}`;
  }, [orgName]);

  // Calculate main content left margin based on sidebar state and screen size
  const mainContentMarginLeft = isMobile ? 0 : sidebarCollapsed ? 64 : 256;

  return (
    <ConfigProvider
      theme={{
        algorithm: theme.darkAlgorithm,
        token: {
          colorPrimary,
          colorBgBase,
          colorBgContainer,
          colorBgElevated: colorBgContainer,
          colorBorder: hexToRgba(colorPrimary, 0.2),
          colorBorderSecondary: 'rgba(255,255,255,0.06)',
          borderRadius: 12,
          colorLink: colorPrimary,
          colorText: 'rgba(255, 255, 255, 0.85)',
          colorTextSecondary: 'rgba(255, 255, 255, 0.65)',
          colorTextTertiary: 'rgba(255, 255, 255, 0.45)',
        },
      }}
    >
      <ChatBarProvider>
        <Layout style={{ minHeight: '100vh', background: colorBgBase }}>
          <PublicNavBar activePath="/gallery" />

          {/* Desktop: Show sidebar, Mobile: Hide */}
          {!isMobile && <MediaSidebar />}

          {/* Main content area */}
          <main
            style={{
              marginLeft: mainContentMarginLeft,
              minHeight: 'calc(100vh - 56px)',
              overflowY: 'auto',
              paddingBottom: 'calc(48px + env(safe-area-inset-bottom, 0px))', // Space for bottom search bar + iOS safe area
              transition: 'margin-left 0.3s ease',
              background: colorBgBase,
            }}
          >
            <div
              style={{
                width: '100%',
                margin: '0 auto',
                padding: isMobile ? '8px 12px' : '12px 12px',
              }}
            >
              <Outlet />
            </div>
          </main>

          {/* Mobile: Show bottom nav, Desktop: Hide */}
          <MediaBottomNav />

          {/* Chat reply notifications */}
          <ChatNotificationToast
            notifications={notifications}
            clearNotification={clearNotification}
          />

          {/* Messenger-style chat bar */}
          <ChatBar />
        </Layout>
      </ChatBarProvider>
    </ConfigProvider>
  );
}
