import React, { ReactNode } from 'react';
import { cn } from '@/lib/utils';
import { GripVertical, Trash2, Copy, ChevronUp, ChevronDown } from 'lucide-react';
import {
    AlertDialog,
    AlertDialogAction,
    AlertDialogCancel,
    AlertDialogContent,
    AlertDialogDescription,
    AlertDialogFooter,
    AlertDialogHeader,
    AlertDialogTitle,
    AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { __ } from '@/lib/i18n';
import { useSortable } from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import { Section } from '../store/usePageEditorStore';

interface CanvasSectionProps {
    section: Section;
    children: ReactNode;
    isSelected: boolean;
    isHovered: boolean;
    onSelect: () => void;
    onHover: () => void;
    onLeave: () => void;
    onDelete: () => void;
    onDuplicate: () => void;
    onMoveUp: () => void;
    onMoveDown: () => void;
    canMoveUp: boolean;
    canMoveDown: boolean;
}

export function CanvasSection({
    section,
    children,
    isSelected,
    isHovered,
    onSelect,
    onHover,
    onLeave,
    onDelete,
    onDuplicate,
    onMoveUp,
    onMoveDown,
    canMoveUp,
    canMoveDown,
}: CanvasSectionProps) {
    const {
        attributes,
        listeners,
        setNodeRef,
        transform,
        transition,
        isDragging,
    } = useSortable({ id: section.id });

    const style = {
        transform: CSS.Transform.toString(transform),
        transition,
    };

    return (
        <div
            ref={setNodeRef}
            style={style}
            className={cn(
                'relative group transition-all duration-200',
                isDragging && 'opacity-50 z-50',
                isSelected && 'ring-2 ring-blue-500 ring-offset-2',
                isHovered && !isSelected && 'ring-1 ring-blue-300'
            )}
            onClick={(e) => {
                e.stopPropagation();
                onSelect();
            }}
            onMouseEnter={onHover}
            onMouseLeave={onLeave}
        >
            {/* Section content with Styles */}
            <div
                className={cn(
                    "relative overflow-hidden rounded-lg",
                    !section.styles?.backgroundColor && !section.styles?.backgroundType && "bg-white/50"
                )}
                style={{
                    ...(section.styles?.backgroundType === 'gradient'
                        ? { background: `linear-gradient(${section.styles?.gradientAngle ?? 135}deg, ${section.styles?.gradientFrom || '#9333ea'}, ${section.styles?.gradientTo || '#3b82f6'})` }
                        : { backgroundColor: section.styles?.backgroundColor }
                    ),
                    paddingTop: section.styles?.paddingTop,
                    paddingBottom: section.styles?.paddingBottom,
                }}
            >
                {/* Background Image & Overlay */}
                {section.styles?.backgroundType === 'image' && section.styles?.backgroundImage && (
                    <>
                        <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 }}
                        />
                    </>
                )}
                {/* Legacy: show bg image even without backgroundType set */}
                {!section.styles?.backgroundType && section.styles?.backgroundImage && (
                    <>
                        <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 }}
                        />
                    </>
                )}

                {/* Dynamic background placeholder (Featured Image) */}
                {section.styles?.backgroundType === 'image'
                    && section.styles?.dynamicBackground === 'post_featured_image'
                    && !section.styles?.backgroundImage && (
                        <>
                            <div
                                className="absolute inset-0 z-0"
                                style={{
                                    backgroundColor: '#e2e8f0',
                                    backgroundImage: 'repeating-linear-gradient(45deg, transparent, transparent 10px, rgba(148,163,184,0.15) 10px, rgba(148,163,184,0.15) 20px)',
                                }}
                            />
                            <div className="absolute inset-0 z-0 flex items-center justify-center pointer-events-none">
                                <div className="flex flex-col items-center gap-1 text-gray-400">
                                    <svg xmlns="http://www.w3.org/2000/svg" className="w-8 h-8" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
                                        <path strokeLinecap="round" strokeLinejoin="round" d="M6.827 6.175A2.31 2.31 0 015.186 7.23c-.38.054-.757.112-1.134.175C2.999 7.58 2.25 8.507 2.25 9.574V18a2.25 2.25 0 002.25 2.25h15A2.25 2.25 0 0021.75 18V9.574c0-1.067-.75-1.994-1.802-2.169a47.865 47.865 0 00-1.134-.175 2.31 2.31 0 01-1.64-1.055l-.822-1.316a2.192 2.192 0 00-1.736-1.039 48.774 48.774 0 00-5.232 0 2.192 2.192 0 00-1.736 1.039l-.821 1.316z" />
                                        <path strokeLinecap="round" strokeLinejoin="round" d="M16.5 12.75a4.5 4.5 0 11-9 0 4.5 4.5 0 019 0z" />
                                    </svg>
                                    <span className="text-xs font-medium">Featured Image</span>
                                </div>
                            </div>
                            {/* Overlay preview */}
                            <div
                                className="absolute inset-0 z-0 bg-black"
                                style={{ opacity: (section.styles.backgroundOverlay || 0) / 100 }}
                            />
                        </>
                    )}

                {/* Content Wrapper */}
                {section.styles?.contentWidth === 'boxed' ? (
                    <div className="relative z-10 container mx-auto px-4 max-w-5xl">
                        <div className="bg-white rounded-2xl shadow-sm border border-gray-200 overflow-hidden">
                            {children}
                        </div>
                    </div>
                ) : (
                    <div className={cn(
                        "relative z-10",
                        section.styles?.contentWidth === 'contained' ? 'container mx-auto px-4 max-w-6xl' : 'w-full'
                    )}>
                        {children}
                    </div>
                )}
            </div>

            {/* Floating Toolbar (Standard Interaction) */}
            {isSelected && (
                <div className="absolute -top-10 right-0 z-50 flex items-center gap-1 bg-white shadow-lg border rounded-lg px-2 py-1 animate-in fade-in slide-in-from-bottom-2">
                    {/* Label */}
                    <span className="text-xs font-semibold text-gray-600 uppercase tracking-wide mr-2 px-1">
                        {section.type.replace('-', ' ')}
                    </span>

                    {/* Divider */}
                    <div className="w-px h-4 bg-gray-200 mx-1" />

                    {/* Actions */}
                    <button
                        onClick={(e) => {
                            e.stopPropagation();
                            onMoveUp();
                        }}
                        disabled={!canMoveUp}
                        className={cn(
                            'p-1.5 rounded text-gray-500 hover:text-black hover:bg-gray-100 transition',
                            !canMoveUp && 'opacity-30 cursor-not-allowed'
                        )}
                        title="Move up"
                    >
                        <ChevronUp className="w-4 h-4" />
                    </button>
                    <button
                        onClick={(e) => {
                            e.stopPropagation();
                            onMoveDown();
                        }}
                        disabled={!canMoveDown}
                        className={cn(
                            'p-1.5 rounded text-gray-500 hover:text-black hover:bg-gray-100 transition',
                            !canMoveDown && 'opacity-30 cursor-not-allowed'
                        )}
                        title="Move down"
                    >
                        <ChevronDown className="w-4 h-4" />
                    </button>
                    <button
                        onClick={(e) => {
                            e.stopPropagation();
                            onDuplicate();
                        }}
                        className="p-1.5 rounded text-gray-500 hover:text-black hover:bg-gray-100 transition"
                        title="Duplicate"
                    >
                        <Copy className="w-4 h-4" />
                    </button>
                    <div className="w-px h-4 bg-gray-200 mx-1" />
                    <div className="w-px h-4 bg-gray-200 mx-1" />

                    <AlertDialog>
                        <AlertDialogTrigger asChild>
                            <button
                                className="p-1.5 rounded text-red-500 hover:text-red-600 hover:bg-red-50 transition"
                                title="Delete"
                            >
                                <Trash2 className="w-4 h-4" />
                            </button>
                        </AlertDialogTrigger>
                        <AlertDialogContent>
                            <AlertDialogHeader>
                                <AlertDialogTitle>{__('Delete this section?')}</AlertDialogTitle>
                                <AlertDialogDescription>
                                    {__('This action cannot be undone.')}
                                </AlertDialogDescription>
                            </AlertDialogHeader>
                            <AlertDialogFooter>
                                <AlertDialogCancel onClick={(e) => e.stopPropagation()}>{__('Cancel')}</AlertDialogCancel>
                                <AlertDialogAction
                                    className="bg-red-600 hover:bg-red-700"
                                    onClick={(e) => {
                                        e.stopPropagation();
                                        onDelete();
                                    }}
                                >
                                    {__('Delete')}
                                </AlertDialogAction>
                            </AlertDialogFooter>
                        </AlertDialogContent>
                    </AlertDialog>
                </div>
            )}

            {/* Active Border Label */}
            {isSelected && (
                <div className="absolute -top-px left-0 bg-blue-500 text-white text-[10px] uppercase font-bold px-2 py-0.5 rounded-b-sm z-10">
                    {section.type}
                </div>
            )}

            {/* Drag Handle (Always visible on hover or select) */}
            {(isSelected || isHovered) && (
                <button
                    {...attributes}
                    {...listeners}
                    className="absolute top-1/2 -left-8 -translate-y-1/2 p-1.5 rounded text-gray-400 hover:text-gray-600 cursor-grab active:cursor-grabbing hover:bg-gray-100"
                    title="Drag to reorder"
                    onClick={(e) => e.stopPropagation()}
                >
                    <GripVertical className="w-5 h-5" />
                </button>
            )}
        </div>
    );
}
