import { useState, useEffect, useMemo } from 'react';
import { ConfigProvider, Layout, theme } from 'antd';
import { Outlet, Link, useNavigate } from 'react-router-dom';
import { useSettingsStore } from '@/stores/settings.store';
import AuthModal from '@/components/AuthModal';
import PublicNavBar from '@/components/PublicNavBar';
import NewsletterSignup from '@/components/public/NewsletterSignup';
import {
  DEFAULT_NAV_ITEMS,
  mergeNavDefaults,
  filterNavItems,
  flattenNavItems,
  buildFeatureFlags,
} from '@/lib/nav-defaults';

const { Content, Footer } = Layout;

export default function PublicLayout() {
  const { settings } = useSettingsStore();
  const navigate = useNavigate();
  const [authModalOpen, setAuthModalOpen] = useState(false);
  const [authModalContext, setAuthModalContext] = useState<'generic' | 'campaign'>('generic');

  const colorPrimary = settings?.publicColorPrimary ?? '#3498db';
  const colorBgBase = settings?.publicColorBgBase ?? '#0d1b2a';
  const colorBgContainer = settings?.publicColorBgContainer ?? '#1b2838';
  const footerText = settings?.footerText ?? 'Powered by Changemaker Lite';

  // Build footer links from navConfig (or defaults) — flatten groups for flat footer
  const footerLinks = useMemo(() => {
    const featureFlags = buildFeatureFlags(settings);
    const merged = mergeNavDefaults(settings?.navConfig?.items ?? DEFAULT_NAV_ITEMS);
    const filtered = filterNavItems(merged, featureFlags);
    const flat = flattenNavItems(filtered);
    return flat
      .filter(item => item.id !== 'home')
      .map(item => ({ label: item.label, path: item.path, external: item.external }));
  }, [settings]);

  // Dynamic document title + favicon for public pages
  useEffect(() => {
    if (!settings) return;
    document.title = settings.organizationName || 'Changemaker Lite';
    if (settings.organizationFaviconUrl) {
      let link = document.querySelector<HTMLLinkElement>("link[rel~='icon']");
      if (!link) {
        link = document.createElement('link');
        link.rel = 'icon';
        document.head.appendChild(link);
      }
      link.href = settings.organizationFaviconUrl;
    }
  }, [settings]);

  return (
    <ConfigProvider
      theme={{
        algorithm: theme.darkAlgorithm,
        token: {
          colorPrimary,
          colorBgBase,
          colorBgContainer,
          colorBgElevated: colorBgContainer,
          colorBorder: 'rgba(255,255,255,0.1)',
          colorBorderSecondary: 'rgba(255,255,255,0.06)',
          borderRadius: 8,
          colorLink: colorPrimary,
        },
      }}
    >
      <Layout style={{ minHeight: '100vh', background: colorBgBase }}>
        <PublicNavBar
          showAuth
          onSignInClick={() => { setAuthModalContext('generic'); setAuthModalOpen(true); }}
        />
        <Content
          style={{
            maxWidth: 960,
            width: '100%',
            margin: '0 auto',
            padding: '24px 16px',
          }}
        >
          <Outlet />
        </Content>
        <Footer
          style={{
            textAlign: 'center',
            background: 'transparent',
            color: 'rgba(255,255,255,0.35)',
            fontSize: 13,
            borderTop: '1px solid rgba(255,255,255,0.06)',
          }}
        >
          <NewsletterSignup />
          <div>{footerText}</div>
          <div style={{ marginTop: 8 }}>
            {footerLinks.map((link, idx) => (
              <span key={link.path}>
                {idx > 0 && ' \u2022 '}
                {link.external ? (
                  <a href={link.path} target="_blank" rel="noopener noreferrer" style={{ color: 'rgba(255,255,255,0.5)', fontSize: 12 }}>
                    {link.label}
                  </a>
                ) : (
                  <Link to={link.path} style={{ color: 'rgba(255,255,255,0.5)', fontSize: 12 }}>
                    {link.label}
                  </Link>
                )}
              </span>
            ))}
          </div>
        </Footer>

        <AuthModal
          open={authModalOpen}
          onCancel={() => setAuthModalOpen(false)}
          onSuccess={() => {
            setAuthModalOpen(false);
            if (authModalContext === 'campaign') {
              navigate('/campaigns/create');
            }
          }}
          title={authModalContext === 'campaign' ? 'Sign in to Create a Campaign' : 'Sign in to your account'}
          subtitle={authModalContext === 'campaign' ? 'Sign in or create an account to submit your own campaign' : 'Sign in or create an account to get involved'}
        />
      </Layout>
    </ConfigProvider>
  );
}
