import { useEffect, useState } from 'react';
import { useParams, Link } from 'react-router-dom';
import { loadSiteDefinition } from '../loaders/loadSiteDefinition';
import { renderLayout } from '../utils/layoutRenderer';
import type { SiteDefinition } from '../types';

function SiteRenderer() {
  const { siteSlug, pageSlug } = useParams<{ siteSlug: string; pageSlug?: string }>();
  const [siteDefinition, setSiteDefinition] = useState<SiteDefinition | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!siteSlug) {
      setError('Site slug is required');
      setLoading(false);
      return;
    }

    loadSiteDefinition(siteSlug)
      .then((definition) => {
        setSiteDefinition(definition);
        setLoading(false);
      })
      .catch((err) => {
        setError(err.message || 'Failed to load site');
        setLoading(false);
      });
  }, [siteSlug, pageSlug]);

  if (loading) {
    return <div>Loading site...</div>;
  }

  if (error) {
    return <div>Error: {error}</div>;
  }

  if (!siteDefinition) {
    return <div>Site not found</div>;
  }

  // Build navigation from site definition
  // Show all published/ready pages (excluding home and draft/generating)
  // Use explicit navigation if available, otherwise auto-generate from pages
  const navigation = siteDefinition.navigation && siteDefinition.navigation.length > 0
    ? siteDefinition.navigation
    : siteDefinition.pages
        .filter(p => 
          p.slug !== 'home' && 
          (p.status === 'published' || p.status === 'ready') &&
          p.status !== 'draft' && 
          p.status !== 'generating'
        )
        .sort((a, b) => (a.order || 0) - (b.order || 0))
        .map(page => ({
          label: page.title,
          slug: page.slug,
          order: page.order || 0
        }));

  // Filter pages based on current route
  const currentPageSlug = pageSlug || 'home';
  const currentPage = siteDefinition.pages.find(p => p.slug === currentPageSlug);
  
  // Show only the current page (home page on home route, specific page on page route)
  const pagesToRender = currentPage
    ? [currentPage]
    : []; // Fallback: no page found

  return (
    <div className="site-renderer" style={{ 
      maxWidth: '1200px', 
      margin: '0 auto', 
      padding: '0 1rem',
      width: '100%'
    }}>
      {/* Navigation Menu */}
      <nav style={{
        padding: '1rem 0',
        borderBottom: '1px solid #e5e7eb',
        marginBottom: '2rem'
      }}>
        <div style={{
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          flexWrap: 'wrap',
          gap: '1rem'
        }}>
          <Link 
            to={`/${siteSlug}`}
            style={{
              fontSize: '1.5rem',
              fontWeight: 'bold',
              textDecoration: 'none',
              color: '#0f172a'
            }}
          >
            {siteDefinition.name}
          </Link>
          <div style={{
            display: 'flex',
            gap: '1.5rem',
            flexWrap: 'wrap'
          }}>
            <Link
              to={`/${siteSlug}`}
              style={{
                textDecoration: 'none',
                color: currentPageSlug === 'home' ? '#4c1d95' : '#64748b',
                fontWeight: currentPageSlug === 'home' ? 600 : 400
              }}
            >
              Home
            </Link>
            {navigation.map((item) => (
              <Link
                key={item.slug}
                to={`/${siteSlug}/${item.slug}`}
                style={{
                  textDecoration: 'none',
                  color: currentPageSlug === item.slug ? '#4c1d95' : '#64748b',
                  fontWeight: currentPageSlug === item.slug ? 600 : 400
                }}
              >
                {item.label}
              </Link>
            ))}
          </div>
        </div>
      </nav>

      {/* Main Content */}
      {renderLayout({ ...siteDefinition, pages: pagesToRender })}

      {/* Footer */}
      <footer style={{
        marginTop: '4rem',
        padding: '2rem 0',
        borderTop: '1px solid #e5e7eb',
        textAlign: 'center',
        color: '#64748b',
        fontSize: '0.875rem'
      }}>
        <p style={{ margin: 0 }}>
          © {new Date().getFullYear()} {siteDefinition.name}. All rights reserved.
        </p>
        {siteDefinition.description && (
          <p style={{ margin: '0.5rem 0 0', fontSize: '0.75rem' }}>
            {siteDefinition.description}
          </p>
        )}
      </footer>
    </div>
  );
}

export default SiteRenderer;

