import React, { useState } from 'react';
import {
    DndContext,
    closestCenter,
    KeyboardSensor,
    PointerSensor,
    useSensor,
    useSensors,
    DragEndEvent,
} from '@dnd-kit/core';
import {
    arrayMove,
    SortableContext,
    sortableKeyboardCoordinates,
    verticalListSortingStrategy,
} from '@dnd-kit/sortable';
import { cn } from '@/lib/utils';
import { Plus, Monitor, Smartphone, LayoutTemplate, GalleryHorizontalEnd, LayoutGrid, Pointer, ScanText } from 'lucide-react';
import { Button } from '@/components/ui/button';
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { CanvasSection } from './CanvasSection';

import { HeroSection } from '../../../../../../customer-spa/src/pages/DynamicPage/sections/HeroSection';
import { ContentSection } from '../../../../../../customer-spa/src/pages/DynamicPage/sections/ContentSection';
import { ImageTextSection } from '../../../../../../customer-spa/src/pages/DynamicPage/sections/ImageTextSection';
import { FeatureGridSection } from '../../../../../../customer-spa/src/pages/DynamicPage/sections/FeatureGridSection';
import { CTABannerSection } from '../../../../../../customer-spa/src/pages/DynamicPage/sections/CTABannerSection';
import { ContactFormSection } from '../../../../../../customer-spa/src/pages/DynamicPage/sections/ContactFormSection';
import { BentoCategoryGrid } from '../../../../../../customer-spa/src/pages/DynamicPage/sections/BentoCategoryGrid';
import { ProductCarousel } from '../../../../../../customer-spa/src/pages/DynamicPage/sections/ProductCarousel';
import { ShoppableImage } from '../../../../../../customer-spa/src/pages/DynamicPage/sections/ShoppableImage';
import { MarqueeBanner } from '../../../../../../customer-spa/src/pages/DynamicPage/sections/MarqueeBanner';
import { normalizeFeatureGridProps, SECTION_SCHEMA_LIST } from '../schema/sectionSchema';

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

interface CanvasRendererProps {
    sections: Section[];
    previewSections?: Section[];
    selectedSectionId: string | null;
    deviceMode: 'desktop' | 'mobile';
    onSelectSection: (id: string | null) => void;
    onAddSection: (type: string, index?: number) => void;
    onDeleteSection: (id: string) => void;
    onDuplicateSection: (id: string) => void;
    onMoveSection: (id: string, direction: 'up' | 'down') => void;
    onReorderSections: (sections: Section[]) => void;

    onDeviceModeChange: (mode: 'desktop' | 'mobile') => void;
    containerWidth?: 'boxed' | 'fullwidth' | 'default';
}

const SECTION_TYPES = [
    { type: 'hero', icon: LayoutTemplate },
    { type: 'content', icon: LayoutTemplate },
    { type: 'image-text', icon: LayoutTemplate },
    { type: 'feature-grid', icon: LayoutTemplate },
    { type: 'cta-banner', icon: LayoutTemplate },
    { type: 'contact-form', icon: LayoutTemplate },
    { type: 'bento-category-grid', icon: LayoutGrid },
    { type: 'product-carousel', icon: GalleryHorizontalEnd },
    { type: 'shoppable-image', icon: Pointer },
    { type: 'marquee-banner', icon: ScanText },
].map((item) => ({
    ...item,
    label: SECTION_SCHEMA_LIST.find((schema) => schema.type === item.type)?.label || item.type,
}));

function flattenSectionProps(section: Section): Record<string, any> {
    const flattened: Record<string, any> = {};
    const props = section.type === 'feature-grid'
        ? normalizeFeatureGridProps(section.props || {})
        : section.props || {};

    for (const [key, value] of Object.entries(props)) {
        if (value && typeof value === 'object' && 'type' in value && 'value' in value) {
            flattened[key] = value.value;
        } else if (value && typeof value === 'object' && 'type' in value && 'source' in value) {
            flattened[key] = `[${value.source}]`;
        } else {
            flattened[key] = value;
        }
    }
    return flattened;
}

function withSectionWrapper(Component: any) {
    return function SectionWrapper({ section, className }: { section: Section; className?: string }) {
        const flatProps = flattenSectionProps(section);
        return (
            <Component 
                id={section.id} 
                layout={section.layoutVariant}
                colorScheme={section.colorScheme}
                elementStyles={section.elementStyles}
                styles={section.styles}
                {...flatProps} 
            />
        );
    }
}

// Map section type to exact customer-spa components via HOC adapter
const SECTION_RENDERERS: Record<string, React.FC<{ section: Section; className?: string }>> = {
    'hero': withSectionWrapper(HeroSection),
    'content': withSectionWrapper(ContentSection),
    'image-text': withSectionWrapper(ImageTextSection),
    'feature-grid': withSectionWrapper(FeatureGridSection),
    'cta-banner': withSectionWrapper(CTABannerSection),
    'contact-form': withSectionWrapper(ContactFormSection),
    'bento-category-grid': withSectionWrapper(BentoCategoryGrid),
    'product-carousel': withSectionWrapper(ProductCarousel),
    'shoppable-image': withSectionWrapper(ShoppableImage),
    'marquee-banner': withSectionWrapper(MarqueeBanner),
};

export function CanvasRenderer({
    sections,
    previewSections,
    selectedSectionId,
    deviceMode,
    onSelectSection,
    onAddSection,
    onDeleteSection,
    onDuplicateSection,
    onMoveSection,
    onReorderSections,

    onDeviceModeChange,
    containerWidth = 'default',
}: CanvasRendererProps) {
    const [hoveredSectionId, setHoveredSectionId] = useState<string | null>(null);
    const previewSectionsById = new Map((previewSections || []).map((section) => [section.id, section]));

    const sensors = useSensors(
        useSensor(PointerSensor, {
            activationConstraint: {
                distance: 8,
            },
        }),
        useSensor(KeyboardSensor, {
            coordinateGetter: sortableKeyboardCoordinates,
        })
    );

    const handleDragEnd = (event: DragEndEvent) => {
        const { active, over } = event;

        if (over && active.id !== over.id) {
            const oldIndex = sections.findIndex(s => s.id === active.id);
            const newIndex = sections.findIndex(s => s.id === over.id);
            const newSections = arrayMove(sections, oldIndex, newIndex);
            onReorderSections(newSections);
        }
    };

    const handleCanvasClick = (e: React.MouseEvent) => {
        // Only deselect if clicking directly on canvas background
        if (e.target === e.currentTarget) {
            onSelectSection(null);
        }
    };

    return (
        <div className="flex-1 flex flex-col bg-gray-100 overflow-hidden">
            {/* Device mode toggle */}
            <div className="flex items-center justify-center gap-2 py-3 bg-white border-b">
                <Button
                    variant={deviceMode === 'desktop' ? 'default' : 'ghost'}
                    size="sm"
                    onClick={() => onDeviceModeChange('desktop')}
                    className="gap-2"
                >
                    <Monitor className="w-4 h-4" />
                    Desktop
                </Button>
                <Button
                    variant={deviceMode === 'mobile' ? 'default' : 'ghost'}
                    size="sm"
                    onClick={() => onDeviceModeChange('mobile')}
                    className="gap-2"
                >
                    <Smartphone className="w-4 h-4" />
                    Mobile
                </Button>
            </div>

            <div
                className={cn(
                    "flex-1 overflow-y-auto",
                    deviceMode === 'desktop' ? "p-0" : "p-6"
                )}
                onClick={handleCanvasClick}
            >
                <div
                    className={cn(
                        'bg-white transition-all duration-300 min-h-[500px]',
                        deviceMode === 'mobile' 
                            ? 'max-w-sm mx-auto shadow-2xl rounded-[2.5rem] border-[12px] border-gray-800 my-8 overflow-hidden' 
                            : 'w-full h-full'
                    )}
                >
                    {sections.length === 0 ? (
                        <div className="py-24 text-center text-gray-400">
                            <LayoutTemplate className="w-16 h-16 mx-auto mb-4 opacity-50" />
                            <p className="text-lg font-medium mb-2">No sections yet</p>
                            <p className="text-sm mb-6">Add your first section to start building</p>
                            <DropdownMenu>
                                <DropdownMenuTrigger asChild>
                                    <Button>
                                        <Plus className="w-4 h-4 mr-2" />
                                        Add Section
                                    </Button>
                                </DropdownMenuTrigger>
                                <DropdownMenuContent>
                                    {SECTION_TYPES.map((type) => (
                                        <DropdownMenuItem
                                            key={type.type}
                                            onClick={() => onAddSection(type.type)}
                                        >
                                            <type.icon className="w-4 h-4 mr-2" />
                                            {type.label}
                                        </DropdownMenuItem>
                                    ))}
                                </DropdownMenuContent>
                            </DropdownMenu>
                        </div>
                    ) : (
                        <div className="flex flex-col">
                            {/* Top Insertion Zone */}
                            <InsertionZone
                                index={0}
                                onAdd={(type) => onAddSection(type, 0)}
                            />

                            <DndContext
                                sensors={sensors}
                                collisionDetection={closestCenter}
                                onDragEnd={handleDragEnd}
                            >
                                <SortableContext
                                    items={sections.map(s => s.id)}
                                    strategy={verticalListSortingStrategy}
                                >
                                    <div className="flex flex-col">
                                        {sections.map((section, index) => {
                                            const Renderer = SECTION_RENDERERS[section.type];
                                            const renderSection = previewSectionsById.get(section.id) || section;

                                            return (
                                                <React.Fragment key={section.id}>
                                                    <CanvasSection
                                                        section={section}
                                                        isSelected={selectedSectionId === section.id}
                                                        isHovered={hoveredSectionId === section.id}
                                                        onSelect={() => onSelectSection(section.id)}
                                                        onHover={() => setHoveredSectionId(section.id)}
                                                        onLeave={() => setHoveredSectionId(null)}
                                                        onDelete={() => onDeleteSection(section.id)}
                                                        onDuplicate={() => onDuplicateSection(section.id)}
                                                        onMoveUp={() => onMoveSection(section.id, 'up')}
                                                        onMoveDown={() => onMoveSection(section.id, 'down')}
                                                        canMoveUp={index > 0}
                                                        canMoveDown={index < sections.length - 1}
                                                    >
                                                        {Renderer ? (
                                                            <Renderer section={renderSection} />
                                                        ) : (
                                                            <div className="p-8 text-center text-gray-400">
                                                                Unknown section type: {section.type}
                                                            </div>
                                                        )}
                                                    </CanvasSection>

                                                    {/* Insertion Zone After Section */}
                                                    <InsertionZone
                                                        index={index + 1}
                                                        onAdd={(type) => onAddSection(type, index + 1)}
                                                    />
                                                </React.Fragment>
                                            );
                                        })}
                                    </div>
                                </SortableContext>
                            </DndContext>
                        </div>
                    )}
                </div>
            </div>
        </div>
    );
}

// Helper: Insertion Zone Component
function InsertionZone({ index, onAdd }: { index: number; onAdd: (type: string) => void }) {
    return (
        <div className="group relative h-4 -my-2 z-10 flex items-center justify-center transition-all hover:h-8 hover:my-0">
            {/* Line */}
            <div className="absolute left-4 right-4 h-0.5 bg-blue-500 opacity-0 group-hover:opacity-100 transition-opacity" />

            {/* Button */}
            <DropdownMenu>
                <DropdownMenuTrigger asChild>
                    <button
                        className="relative z-10 w-6 h-6 rounded-full bg-blue-500 text-white flex items-center justify-center opacity-0 group-hover:opacity-100 transition-all hover:scale-110 shadow-sm"
                        title="Add Section Here"
                    >
                        <Plus className="w-4 h-4" />
                    </button>
                </DropdownMenuTrigger>
                <DropdownMenuContent>
                    {SECTION_TYPES.map((type) => (
                        <DropdownMenuItem
                            key={type.type}
                            onClick={() => onAdd(type.type)}
                        >
                            <type.icon className="w-4 h-4 mr-2" />
                            {type.label}
                        </DropdownMenuItem>
                    ))}
                </DropdownMenuContent>
            </DropdownMenu>
        </div>
    );
}
