import { FC, useEffect } from 'react'
import { useEmailBuilderStore } from '../../store/builderStore'
import BlockRenderer from './BlockRenderer'

interface CanvasProps {
    className?: string
}

const Canvas: FC<CanvasProps> = ({ className = '' }) => {
    const {
        template,
        selectedBlockId,
        selectBlock,
        updateBlock,
        removeBlock,
        isPreviewMode
    } = useEmailBuilderStore()

    // Handle keyboard events
    useEffect(() => {
        const handleKeyDown = (e: KeyboardEvent) => {
            if (selectedBlockId && (e.key === 'Delete' || e.key === 'Backspace')) {
                e.preventDefault()
                removeBlock(selectedBlockId)
            }

            if (e.key === 'Escape') {
                selectBlock(null)
            }
        }

        document.addEventListener('keydown', handleKeyDown)
        return () => document.removeEventListener('keydown', handleKeyDown)
    }, [selectedBlockId, removeBlock, selectBlock])

    // Handle canvas click (deselect blocks)
    const handleCanvasClick = (e: React.MouseEvent) => {
        if (e.target === e.currentTarget) {
            selectBlock(null)
        }
    }

    const canvasStyle = {
        width: `${template.settings.width}px`,
        maxWidth: '100%',
        backgroundColor: template.settings.backgroundColor,
        fontFamily: template.settings.fontFamily,
        direction: template.settings.rtl ? 'rtl' as const : 'ltr' as const,
        minHeight: '400px',
        margin: '0 auto',
        padding: '20px',
        borderRadius: '12px',
        boxShadow: '0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)',
        position: 'relative' as const
    }

    return (
        <div className={`bg-gray-50 p-6 rounded-4xl ${className}`}>
            {/* Canvas Header */}
            <div className="mb-4 flex items-center justify-between">
                <div>
                    <h3 className="text-lg font-semibold text-gray-900">
                        {template.name}
                    </h3>
                    <p className="text-sm text-gray-600">
                        {template.blocks.length} بلوک • عرض {template.settings.width}px
                    </p>
                </div>

                {selectedBlockId && (
                    <div className="text-sm text-blue-600 bg-blue-50 px-3 py-1 rounded-lg">
                        بلوک انتخاب شده
                    </div>
                )}
            </div>

            {/* Canvas Area */}
            <div
                className="canvas-area bg-white border-2 border-dashed border-gray-300 rounded-xl p-4 min-h-[400px] overflow-auto"
                onClick={handleCanvasClick}
                style={{
                    maxHeight: 'calc(100vh - 200px)'
                }}
            >
                <div style={canvasStyle}>
                    {template.blocks.length === 0 ? (
                        <div className="text-center py-16 text-gray-500">
                            <div className="text-4xl mb-4">📧</div>
                            <h4 className="text-lg font-medium mb-2">قالب خالی است</h4>
                            <p className="text-sm">
                                از سایدبار سمت راست، بلوک‌های مورد نیاز را اضافه کنید
                            </p>
                        </div>
                    ) : (
                        <div className="space-y-2">
                            {template.blocks.map((block) => (
                                <div key={block.id} className="block-wrapper">
                                    <BlockRenderer
                                        block={block}
                                        isSelected={selectedBlockId === block.id}
                                        onUpdate={(updates) => updateBlock(block.id, updates)}
                                        onSelect={() => selectBlock(block.id)}
                                        isEditing={selectedBlockId === block.id && !isPreviewMode}
                                    />
                                </div>
                            ))}
                        </div>
                    )}
                </div>
            </div>

            {/* Canvas Footer */}
            <div className="mt-4 flex items-center justify-between text-xs text-gray-500">
                <div>
                    {template.variables.length > 0 && (
                        <span>
                            {template.variables.length} متغیر تعریف شده
                        </span>
                    )}
                </div>

                <div className="flex gap-4">
                    <span>📱 موبایل: {template.settings.width <= 480 ? '✅' : '⚠️'}</span>
                    <span>🖥️ دسکتاپ: ✅</span>
                    <span>📧 ایمیل: ✅</span>
                </div>
            </div>

            {/* Instructions */}
            {template.blocks.length > 0 && (
                <div className="mt-4 p-3 bg-blue-50 rounded-lg">
                    <p className="text-xs text-blue-700">
                        💡 <strong>راهنما:</strong> روی بلوک‌ها کلیک کنید تا ویرایش شوند •
                        کلید Delete برای حذف • Escape برای لغو انتخاب
                    </p>
                </div>
            )}
        </div>
    )
}

export default Canvas 