import React from 'react';
import { cn } from '@/lib/utils';
import { SharedContentLayout } from '@/components/SharedContentLayout';
import { getSectionBackground } from '@/lib/sectionStyles';

interface ContentSectionProps {
    id?: string;
    section: {
        id: string;
        layoutVariant?: string;
        colorScheme?: string;
        elementStyles?: Record<string, any>;
        styles?: Record<string, any>;
        props?: any;
    };
    content?: string;
    cta_text?: string;
    cta_url?: string;
}

const COLOR_SCHEMES: Record<string, { bg: string; text: string }> = {
    default: { bg: 'bg-white', text: 'text-gray-900' },
    light: { bg: 'bg-gray-50', text: 'text-gray-900' },
    dark: { bg: 'bg-gray-900', text: 'text-white' },
    blue: { bg: 'wn-primary-bg', text: 'text-white' },
    primary: { bg: 'wn-primary-bg', text: 'text-white' },
    secondary: { bg: 'wn-secondary-bg', text: 'text-white' },
    muted: { bg: 'bg-gray-50', text: 'text-gray-700' },
};

const fontSizeToCSS = (className?: string) => {
    switch (className) {
        case 'text-xs': return '0.75rem';
        case 'text-sm': return '0.875rem';
        case 'text-base': return '1rem';
        case 'text-lg': return '1.125rem';
        case 'text-xl': return '1.25rem';
        case 'text-2xl': return '1.5rem';
        case 'text-3xl': return '1.875rem';
        case 'text-4xl': return '2.25rem';
        case 'text-5xl': return '3rem';
        case 'text-6xl': return '3.75rem';
        case 'text-7xl': return '4.5rem';
        case 'text-8xl': return '6rem';
        case 'text-9xl': return '8rem';
        default: return undefined;
    }
};

const fontWeightToCSS = (className?: string) => {
    switch (className) {
        case 'font-thin': return '100';
        case 'font-extralight': return '200';
        case 'font-light': return '300';
        case 'font-normal': return '400';
        case 'font-medium': return '500';
        case 'font-semibold': return '600';
        case 'font-bold': return '700';
        case 'font-extrabold': return '800';
        case 'font-black': return '900';
        default: return undefined;
    }
};

// Helper to generate scoped CSS for prose elements
const generateScopedStyles = (sectionId: string, elementStyles: Record<string, any>) => {
    const styles: string[] = [];
    const scope = `#${sectionId}`; // ContentSection uses id directly on section tag

    // Headings (h1-h4)
    const hs = elementStyles?.heading;
    if (hs) {
        const headingRules = [
            hs.color && `color: ${hs.color} !important;`,
            hs.fontWeight && `font-weight: ${fontWeightToCSS(hs.fontWeight)} !important;`,
            hs.fontFamily && `font-family: var(--font-${hs.fontFamily}, inherit) !important;`,
            hs.fontSize && `font-size: ${fontSizeToCSS(hs.fontSize)} !important;`,
            hs.backgroundColor && `background-color: ${hs.backgroundColor} !important;`,
            hs.backgroundColor && `padding: 0.2em 0.4em; border-radius: 4px; display: inline-block;`,
        ].filter(Boolean).join(' ');
        if (headingRules) {
            styles.push(`${scope} h1, ${scope} h2, ${scope} h3, ${scope} h4 { ${headingRules} }`);
        }
    }

    // Body text (p, li)
    const ts = elementStyles?.text;
    if (ts) {
        const textRules = [
            ts.color && `color: ${ts.color} !important;`,
            ts.fontSize && `font-size: ${fontSizeToCSS(ts.fontSize)} !important;`,
            ts.fontWeight && `font-weight: ${fontWeightToCSS(ts.fontWeight)} !important;`,
            ts.fontFamily && `font-family: var(--font-${ts.fontFamily}, inherit) !important;`,
        ].filter(Boolean).join(' ');
        if (textRules) {
            styles.push(`${scope} p, ${scope} li, ${scope} ul, ${scope} ol { ${textRules} }`);
        }
    }

    // Explicit Spacing & List Formatting Restorations
    styles.push(`
        ${scope} p { margin-bottom: 1em; }
        ${scope} h1, ${scope} h2, ${scope} h3, ${scope} h4 { margin-top: 1.5em; margin-bottom: 0.5em; line-height: 1.2; }
        ${scope} ul { list-style-type: disc; padding-left: 1.5em; margin-bottom: 1em; }
        ${scope} ol { list-style-type: decimal; padding-left: 1.5em; margin-bottom: 1em; }
        ${scope} li { margin-bottom: 0.25em; }
        ${scope} img { margin-top: 1.5em; margin-bottom: 1.5em; }
    `);

    // Links (a:not(.button))
    const ls = elementStyles?.link;
    if (ls) {
        const linkRules = [
            ls.color && `color: ${ls.color} !important;`,
            ls.textDecoration && `text-decoration: ${ls.textDecoration} !important;`,
            ls.fontSize && `font-size: ${fontSizeToCSS(ls.fontSize)} !important;`,
            ls.fontWeight && `font-weight: ${fontWeightToCSS(ls.fontWeight)} !important;`,
        ].filter(Boolean).join(' ');
        if (linkRules) {
            styles.push(`${scope} a:not([data-button]):not(.button) { ${linkRules} }`);
        }
        if (ls.hoverColor) {
            styles.push(`${scope} a:not([data-button]):not(.button):hover { color: ${ls.hoverColor} !important; }`);
        }
    }

    // Buttons (a[data-button], .button)
    const bs = elementStyles?.button;
    if (bs) {
        const btnRules = [
            bs.backgroundColor && `background-color: ${bs.backgroundColor} !important;`,
            bs.color && `color: ${bs.color} !important;`,
            bs.borderRadius && `border-radius: ${bs.borderRadius} !important;`,
            bs.padding && `padding: ${bs.padding} !important;`,
            bs.fontSize && `font-size: ${fontSizeToCSS(bs.fontSize)} !important;`,
            bs.fontWeight && `font-weight: ${fontWeightToCSS(bs.fontWeight)} !important;`,
            bs.borderColor && `border: ${bs.borderWidth || '1px'} solid ${bs.borderColor} !important;`,
        ].filter(Boolean).join(' ');

        styles.push(`${scope} a[data-button], ${scope} .button { ${btnRules} display: inline-block; text-decoration: none !important; }`);
        styles.push(`${scope} a[data-button]:hover, ${scope} .button:hover { opacity: 0.9; }`);
    }

    // Images
    const is = elementStyles?.image;
    if (is) {
        const imgRules = [
            is.objectFit && `object-fit: ${is.objectFit} !important;`,
            is.borderRadius && `border-radius: ${is.borderRadius} !important;`,
            is.width && `width: ${is.width} !important;`,
            is.height && `height: ${is.height} !important;`,
        ].filter(Boolean).join(' ');
        if (imgRules) {
            styles.push(`${scope} img { ${imgRules} }`);
        }
    }

    return styles.join('\n');
};

export function ContentSection({ section, content: propContent, cta_text: propCtaText, cta_url: propCtaUrl }: ContentSectionProps & { outerPadding?: boolean }) {
    const scheme = COLOR_SCHEMES[section.colorScheme || 'default'] ?? COLOR_SCHEMES['default'];
    // Default to 'default' width if not specified
    const _layout = section.layoutVariant || 'default';

    const heightPreset = section.styles?.heightPreset || 'default';

    const heightMap: Record<string, string> = {
        'default': 'py-12 md:py-20',
        'small': 'py-8 md:py-12',
        'medium': 'py-16 md:py-24',
        'large': 'py-24 md:py-32',
        'screen': 'min-h-screen py-20 flex items-center',
    };

    const heightClasses = heightMap[heightPreset] || 'py-12 md:py-20';

    const content = propContent || section.props?.content?.value || section.props?.content || '';

    // Helper to get text styles
    const getTextStyles = (elementName: string) => {
        const styles = section.elementStyles?.[elementName] || {};
        return {
            classNames: cn(
                styles.fontSize,
                styles.fontWeight,
                {
                    'font-sans': styles.fontFamily === 'secondary',
                    'font-serif': styles.fontFamily === 'primary',
                }
            ),
            style: {
                color: styles.color,
                textAlign: styles.textAlign,
                backgroundColor: styles.backgroundColor
            }
        };
    };

    const contentStyle = getTextStyles('content');
    const headingStyle = getTextStyles('heading');
    const textStyle = getTextStyles('text');
    const buttonStyle = getTextStyles('button');

    const containerWidth = section.styles?.contentWidth ?? 'contained';
    const cta_text = propCtaText || section.props?.cta_text?.value || section.props?.cta_text;
    const cta_url = propCtaUrl || section.props?.cta_url?.value || section.props?.cta_url;

    const hasCustomBackground = !!section.styles?.backgroundColor || !!section.styles?.backgroundImage || section.styles?.backgroundType === 'gradient';
    const sectionBg = getSectionBackground(section.styles);

    // Helper to get background style for dynamic schemes
    const getBackgroundStyle = (): React.CSSProperties | undefined => {
        if (hasCustomBackground) return sectionBg.style;
        if (scheme.bg === 'wn-primary-bg') {
            return { backgroundColor: 'var(--wn-primary, #1a1a1a)' };
        }
        if (scheme.bg === 'wn-secondary-bg') {
            return { backgroundColor: 'var(--wn-secondary, #6b7280)' };
        }
        return undefined;
    };

    return (
        <>
            <style dangerouslySetInnerHTML={{ __html: generateScopedStyles(section.id, section.elementStyles || {}) }} />
            <section
                id={section.id}
                className={cn(
                    'wn-content',
                    heightClasses,
                    !hasCustomBackground && !scheme.bg.startsWith('wn-') && scheme.bg,
                    scheme.text
                )}
                style={getBackgroundStyle()}
            >
                <SharedContentLayout
                    text={content}
                    textStyle={textStyle.style}
                    headingStyle={headingStyle.style}
                    containerWidth={containerWidth as any}
                    className={contentStyle.classNames}
                    buttons={cta_text && cta_url ? [{ text: cta_text, url: cta_url }] : []}
                    buttonStyle={{
                        classNames: buttonStyle.classNames,
                        style: buttonStyle.style
                    }}
                />
            </section>
        </>
    );
}
