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';
import { BentoCategoryGrid } from './sections/BentoCategoryGrid';
import { ProductCarousel } from './sections/ProductCarousel';
import { ShoppableImage } from './sections/ShoppableImage';
import { MarqueeBanner } from './sections/MarqueeBanner';

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

interface SectionStyles {
    backgroundColor?: string;
    backgroundImage?: string;
    backgroundType?: 'color' | 'image' | 'gradient';
    backgroundOverlay?: number;
    paddingTop?: string;
    paddingBottom?: string;
    contentWidth?: 'full' | 'contained';
}

interface ElementStyle {
    color?: string;
    fontSize?: string;
    fontWeight?: string;
    textAlign?: 'left' | 'center' | 'right';
}

interface Section {
    id: string;
    type: string;
    layoutVariant?: string;
    colorScheme?: string;
    styles?: SectionStyles;
    elementStyles?: Record<string, ElementStyle>;
    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;
    };
    container_width?: string;
    effective_container_width?: 'boxed' | 'fullwidth';
    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,
    'bento-category-grid': BentoCategoryGrid,
    'bento_category_grid': BentoCategoryGrid,
    'product-carousel': ProductCarousel,
    'product_carousel': ProductCarousel,
    'shoppable-image': ShoppableImage,
    'shoppable_image': ShoppableImage,
    'marquee-banner': MarqueeBanner,
    'marquee_banner': MarqueeBanner,
};

/**
 * Flatten section props by extracting .value from {type, value} objects
 * This transforms { title: { type: 'static', value: 'Hello' } }
 * into { title: 'Hello' }
 */
function flattenSectionProps(props: Record<string, any>): Record<string, any> {
    const flattened: Record<string, any> = {};

    for (const [key, value] of Object.entries(props)) {
        if (value && typeof value === 'object' && 'type' in value && 'value' in value) {
            // This is a {type, value} prop structure
            flattened[key] = value.value;
        } else if (value && typeof value === 'object' && 'type' in value && 'source' in value) {
            // This is a dynamic prop - use source as placeholder for now
            flattened[key] = `[${value.source}]`;
        } else {
            // Regular value, pass through
            flattened[key] = value;
        }
    }

    if (flattened.items === undefined && flattened.features !== undefined) {
        flattened.items = flattened.features;
    }

    return flattened;
}

/**
 * DynamicPageRenderer
 * Renders structural pages and CPT template content
 */
interface DynamicPageRendererProps {
    slug?: string;
}

export function DynamicPageRenderer({ slug: propSlug }: DynamicPageRendererProps) {
    const { pathBase, slug: paramSlug } = useParams<{ pathBase?: string; slug?: string }>();
    const navigate = useNavigate();
    const [notFound, setNotFound] = useState(false);

    // Get page type from DOM (injected by TemplateOverride.php)
    const appEl = document.getElementById('woonoow-customer-app');
    const dataPageType = appEl?.getAttribute('data-page');
    const dataCptType = appEl?.getAttribute('data-cpt-type');   // e.g. 'post', 'portfolio'
    const dataCptSlug = appEl?.getAttribute('data-cpt-slug');   // e.g. 'my-post-slug'

    // Determine content type:
    // Priority: pathBase from router > data-cpt-type from DOM > fallback
    const contentType = pathBase
        ? (pathBase === 'blog' ? 'post' : pathBase)
        : (dataPageType === 'cpt' && dataCptType ? dataCptType : undefined);

    // Effective slug: prefer router param, then DOM cpt-slug
    const effectiveSlug = propSlug || paramSlug || (dataPageType === 'cpt' ? dataCptSlug : undefined) || '';

    // Determine if this is a page or CPT content
    const isStructuralPage = dataPageType === 'page' || dataPageType === 'shop' || contentType === undefined;

    const contentSlug = effectiveSlug;

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

    // Handle 404
    useEffect(() => {
        if (error) {
            // eslint-disable-next-line react-hooks/set-state-in-effect
            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>
                <div className="bg-gray-100 p-4 rounded text-left mb-8 text-sm">
                    <strong>DEBUG INFO:</strong><br />
                    pathBase: {pathBase ?? 'undefined'}<br />
                    propSlug: {propSlug ?? 'undefined'}<br />
                    paramSlug: {paramSlug ?? 'undefined'}<br />
                    effectiveSlug: {effectiveSlug ?? 'undefined'}<br />
                    dataPageType: {dataPageType ?? 'undefined'}<br />
                    contentType: {contentType ?? 'undefined'}<br />
                    isStructuralPage: {isStructuralPage ? 'true' : 'false'}<br />
                </div>
                <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 using effective container width */}
            <div className={`wn-page ${pageData.effective_container_width === 'boxed' ? 'container mx-auto px-4 max-w-6xl' : ''}`}>
                {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 (
                        <div
                            key={section.id}
                            className="relative overflow-hidden"
                            style={{
                                // Only explicit custom padding overrides from the padding fields
                                paddingTop: section.styles?.paddingTop,
                                paddingBottom: section.styles?.paddingBottom,
                            }}
                        >
                            {/* Full-bleed background image & overlay */}
                            {section.styles?.backgroundImage && (section.styles.backgroundType === 'image' || !section.styles.backgroundType) && (
                                <>
                                    <div
                                        className="absolute inset-0 z-0 bg-cover bg-center bg-no-repeat"
                                        style={{ backgroundImage: `url(${section.styles.backgroundImage})` }}
                                    />
                                    <div
                                        className="absolute inset-0 z-0 bg-black"
                                        style={{ opacity: (section.styles.backgroundOverlay || 0) / 100 }}
                                    />
                                </>
                            )}

                            {/* Section component — manages its own background, height, and inner content width */}
                            <div className="relative z-10 w-full">
                                <SectionComponent
                                    id={section.id}
                                    section={section}
                                    layout={section.layoutVariant || 'default'}
                                    colorScheme={section.colorScheme || 'default'}
                                    styles={section.styles}
                                    elementStyles={section.elementStyles}
                                    {...flattenSectionProps(section.props || {})}
                                />
                            </div>
                        </div>
                    );
                })}

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