import { useEffect, useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import { api } from '@/lib/api/client';
import { Helmet } from 'react-helmet-async';

// Section Components
import { HeroSection } from './sections/HeroSection';
import { ContentSection } from './sections/ContentSection';
import { ImageTextSection } from './sections/ImageTextSection';
import { FeatureGridSection } from './sections/FeatureGridSection';
import { CTABannerSection } from './sections/CTABannerSection';
import { ContactFormSection } from './sections/ContactFormSection';

// Types
interface SectionProp {
    type: 'static' | 'dynamic';
    value?: any;
    source?: string;
}

interface Section {
    id: string;
    type: string;
    layoutVariant?: string;
    colorScheme?: string;
    props: Record<string, SectionProp | any>;
}

interface PageData {
    id?: number;
    type: 'page' | 'content';
    slug?: string;
    title?: string;
    url?: string;
    seo?: {
        meta_title?: string;
        meta_description?: string;
        canonical?: string;
        og_title?: string;
        og_description?: string;
        og_image?: string;
    };
    structure?: {
        sections: Section[];
    };
    post?: Record<string, any>;
    rendered?: {
        sections: Section[];
    };
}

// Section renderer map
const SECTION_COMPONENTS: Record<string, React.ComponentType<any>> = {
    hero: HeroSection,
    content: ContentSection,
    'image-text': ImageTextSection,
    'image_text': ImageTextSection,
    'feature-grid': FeatureGridSection,
    'feature_grid': FeatureGridSection,
    'cta-banner': CTABannerSection,
    'cta_banner': CTABannerSection,
    'contact-form': ContactFormSection,
    'contact_form': ContactFormSection,
};

/**
 * DynamicPageRenderer
 * Renders structural pages and CPT template content
 */
export function DynamicPageRenderer() {
    const { pathBase, slug } = useParams<{ pathBase?: string; slug?: string }>();
    const navigate = useNavigate();
    const [notFound, setNotFound] = useState(false);

    // Determine if this is a page or CPT content
    const isStructuralPage = !pathBase;
    const contentType = pathBase === 'blog' ? 'post' : pathBase;
    const contentSlug = slug || '';

    // Fetch page/content data
    const { data: pageData, isLoading, error } = useQuery<PageData>({
        queryKey: ['dynamic-page', pathBase, slug],
        queryFn: async (): Promise<PageData> => {
            if (isStructuralPage) {
                // Fetch structural page
                const response = await api.get(`/pages/${slug}`);
                return response.data;
            } else {
                // Fetch CPT content with template
                const response = await api.get(`/content/${contentType}/${contentSlug}`);
                return response.data;
            }
        },
        retry: false,
        staleTime: 5 * 60 * 1000, // Cache for 5 minutes
    });

    // Handle 404
    useEffect(() => {
        if (error) {
            setNotFound(true);
        }
    }, [error]);

    // Get sections to render
    const sections = isStructuralPage
        ? pageData?.structure?.sections || []
        : pageData?.rendered?.sections || [];

    // Loading state
    if (isLoading) {
        return (
            <div className="flex items-center justify-center min-h-[50vh]">
                <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary"></div>
            </div>
        );
    }

    // 404 state
    if (notFound || !pageData) {
        return (
            <div className="flex flex-col items-center justify-center min-h-[50vh] text-center">
                <h1 className="text-4xl font-bold text-gray-900 mb-4">404</h1>
                <p className="text-gray-600 mb-8">Page not found</p>
                <button
                    onClick={() => navigate('/')}
                    className="px-6 py-2 bg-primary text-white rounded-lg hover:bg-primary/90"
                >
                    Go Home
                </button>
            </div>
        );
    }

    return (
        <>
            {/* SEO */}
            <Helmet>
                <title>{pageData.seo?.meta_title || pageData.title || 'Page'}</title>
                {pageData.seo?.meta_description && (
                    <meta name="description" content={pageData.seo.meta_description} />
                )}
                {pageData.seo?.canonical && (
                    <link rel="canonical" href={pageData.seo.canonical} />
                )}
                {pageData.seo?.og_title && (
                    <meta property="og:title" content={pageData.seo.og_title} />
                )}
                {pageData.seo?.og_description && (
                    <meta property="og:description" content={pageData.seo.og_description} />
                )}
                {pageData.seo?.og_image && (
                    <meta property="og:image" content={pageData.seo.og_image} />
                )}
            </Helmet>

            {/* Render sections */}
            <div className="wn-page">
                {sections.map((section) => {
                    const SectionComponent = SECTION_COMPONENTS[section.type];

                    if (!SectionComponent) {
                        // Fallback for unknown section types
                        return (
                            <div key={section.id} className={`wn-section wn-${section.type}`}>
                                <pre className="text-xs text-gray-500">
                                    Unknown section type: {section.type}
                                </pre>
                            </div>
                        );
                    }

                    return (
                        <SectionComponent
                            key={section.id}
                            id={section.id}
                            layout={section.layoutVariant || 'default'}
                            colorScheme={section.colorScheme || 'default'}
                            {...section.props}
                        />
                    );
                })}

                {/* Empty state */}
                {sections.length === 0 && (
                    <div className="py-20 text-center text-gray-500">
                        <p>This page has no content yet.</p>
                    </div>
                )}
            </div>
        </>
    );
}
