import { motion, AnimatePresence, Reorder } from 'framer-motion'
import { useState, useCallback } from 'react'
import { GripVertical, Type, Image, BookOpen, MessageSquare, Minus, Plus, Trash2, MoveUp, MoveDown, Eye } from 'lucide-react'
import { Button } from '@/Components/ui/Button'
import { cn } from '@/lib/utils'

interface Block {
    id: string
    type: 'text' | 'button' | 'support' | 'faq' | 'divider' | 'image'
    content: string
    settings?: Record<string, any>
}

interface PageBuilderProps {
    blocks: Block[]
    onChange: (blocks: Block[]) => void
    vendorAccent?: string
    readOnly?: boolean
}

const blockTypes = [
    { type: 'text' as const, icon: Type, label: 'Text', defaultContent: 'Enter your text here...' },
    { type: 'button' as const, icon: Eye, label: 'Button', defaultContent: 'Download Now' },
    { type: 'support' as const, icon: MessageSquare, label: 'Support', defaultContent: 'Need help? Contact us' },
    { type: 'faq' as const, icon: BookOpen, label: 'FAQ', defaultContent: 'Q: How to download?\nA: Click the button below.' },
    { type: 'divider' as const, icon: Minus, label: 'Divider', defaultContent: '' },
    { type: 'image' as const, icon: Image, label: 'Image', defaultContent: 'https://' },
]

export function PageBuilder({ blocks, onChange, vendorAccent = '#22d3ee', readOnly = false }: PageBuilderProps) {
    const [selectedBlockId, setSelectedBlockId] = useState<string | null>(null)
    const [previewMode, setPreviewMode] = useState(false)

    const addBlock = (type: Block['type']) => {
        const template = blockTypes.find(b => b.type === type)!
        const newBlock: Block = {
            id: Math.random().toString(36).slice(2, 10),
            type,
            content: template.defaultContent,
            settings: {},
        }
        onChange([...blocks, newBlock])
        setSelectedBlockId(newBlock.id)
    }

    const updateBlock = (id: string, data: Partial<Block>) => {
        onChange(blocks.map(b => b.id === id ? { ...b, ...data } : b))
    }

    const removeBlock = (id: string) => {
        onChange(blocks.filter(b => b.id !== id))
        if (selectedBlockId === id) setSelectedBlockId(null)
    }

    const moveBlock = (id: string, direction: 'up' | 'down') => {
        const idx = blocks.findIndex(b => b.id === id)
        if (idx < 0) return
        if (direction === 'up' && idx === 0) return
        if (direction === 'down' && idx === blocks.length - 1) return

        const newBlocks = [...blocks]
        const swapIdx = direction === 'up' ? idx - 1 : idx + 1;
        [newBlocks[idx], newBlocks[swapIdx]] = [newBlocks[swapIdx], newBlocks[idx]]
        onChange(newBlocks)
    }

    const renderBlockPreview = (block: Block) => {
        switch (block.type) {
            case 'text':
                return <p className="text-sm text-slate-300 whitespace-pre-wrap">{block.content}</p>
            case 'button':
                return (
                    <div className="py-2 px-6 rounded-xl text-sm font-medium text-white inline-block" style={{ background: vendorAccent }}>
                        {block.content || 'Button'}
                    </div>
                )
            case 'support':
                return (
                    <div className="glass rounded-xl p-4 border-white/10">
                        <p className="text-sm text-slate-300">{block.content}</p>
                    </div>
                )
            case 'faq':
                return (
                    <details className="glass rounded-xl p-4 border-white/10">
                        <summary className="text-sm font-medium text-white cursor-pointer">{block.content.split('\n')[0]}</summary>
                        <p className="text-xs text-slate-400 mt-2">{block.content.split('\n').slice(1).join('\n')}</p>
                    </details>
                )
            case 'divider':
                return <hr className="border-white/10" />
            case 'image':
                return block.content?.startsWith('http') ? (
                    <img src={block.content} alt="" className="w-full max-w-xs rounded-xl" />
                ) : (
                    <div className="w-full h-24 glass rounded-xl flex items-center justify-center text-slate-500 text-xs">Image URL</div>
                )
            default:
                return null
        }
    }

    return (
        <div className="flex gap-4 min-h-[500px]">
            {/* Left Panel: Block Library */}
            {!readOnly && (
                <div className="w-44 shrink-0 glass rounded-2xl p-3 border-white/10">
                    <p className="text-[10px] font-semibold text-slate-500 uppercase tracking-wider mb-3 px-2">Blocks</p>
                    <div className="space-y-1">
                        {blockTypes.map(bt => (
                            <button key={bt.type} onClick={() => addBlock(bt.type)}
                                className="w-full flex items-center gap-2 px-3 py-2 rounded-xl text-xs text-slate-400 hover:text-white hover:bg-white/5 transition-all text-left">
                                <bt.icon className="w-3.5 h-3.5 text-slate-500" /> {bt.label}
                            </button>
                        ))}
                    </div>
                    <div className="mt-4 pt-3 border-t border-white/5">
                        <Button size="sm" variant="ghost" className="w-full text-xs"
                            onClick={() => setPreviewMode(!previewMode)}>
                            <Eye className="w-3 h-3 mr-1" /> {previewMode ? 'Edit' : 'Preview'}
                        </Button>
                    </div>
                </div>
            )}

            {/* Center: Canvas */}
            <div className="flex-1 glass rounded-2xl p-4 border-white/10 overflow-y-auto max-h-[600px]">
                {blocks.length === 0 && (
                    <div className="flex items-center justify-center h-full text-slate-500 text-sm">
                        {readOnly ? 'No content' : 'Add blocks from the left panel to build your page'}
                    </div>
                )}
                <AnimatePresence>
                    {blocks.map((block, i) => (
                        <motion.div key={block.id}
                            initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }}
                            exit={{ opacity: 0, x: -50 }}
                            className={cn(
                                'group relative p-3 rounded-xl mb-2 transition-all',
                                selectedBlockId === block.id && !previewMode ? 'bg-white/5 ring-1 ring-cyan-500/30' : 'hover:bg-white/[0.02]'
                            )}
                            onClick={() => !previewMode && setSelectedBlockId(block.id)}>
                            {!previewMode && !readOnly && (
                                <div className="absolute -right-1 -top-1 flex gap-0.5 opacity-0 group-hover:opacity-100 transition-opacity">
                                    <button onClick={() => removeBlock(block.id)} className="p-1 rounded bg-red-500/20 text-red-400 hover:bg-red-500/30"><Trash2 className="w-3 h-3" /></button>
                                    <button onClick={() => moveBlock(block.id, 'up')} className="p-1 rounded bg-white/10 text-slate-400 hover:bg-white/20"><MoveUp className="w-3 h-3" /></button>
                                    <button onClick={() => moveBlock(block.id, 'down')} className="p-1 rounded bg-white/10 text-slate-400 hover:bg-white/20"><MoveDown className="w-3 h-3" /></button>
                                </div>
                            )}
                            {previewMode || readOnly ? renderBlockPreview(block) : (
                                <div>
                                    <div className="flex items-center gap-2 mb-2">
                                        <GripVertical className="w-3 h-3 text-slate-600" />
                                        <span className="text-[10px] text-slate-500 uppercase">{block.type}</span>
                                    </div>
                                    {block.type !== 'divider' && (
                                        <textarea
                                            value={block.content}
                                            onChange={e => updateBlock(block.id, { content: e.target.value })}
                                            className="w-full bg-transparent text-sm text-white resize-none outline-none placeholder:text-slate-600"
                                            rows={block.type === 'faq' ? 4 : block.type === 'text' ? 3 : 1}
                                            placeholder={`Enter ${block.type} content...`}
                                            onClick={e => e.stopPropagation()}
                                        />
                                    )}
                                    {block.type === 'divider' && <hr className="border-white/10 my-2" />}
                                </div>
                            )}
                        </motion.div>
                    ))}
                </AnimatePresence>
            </div>

            {/* Right Panel: Settings (future: colors, spacing, animations) */}
            {selectedBlockId && !previewMode && !readOnly && (
                <div className="w-44 shrink-0 glass rounded-2xl p-3 border-white/10">
                    <p className="text-[10px] font-semibold text-slate-500 uppercase tracking-wider mb-3 px-2">Settings</p>
                    {(() => {
                        const block = blocks.find(b => b.id === selectedBlockId)
                        if (!block) return null
                        return (
                            <div className="space-y-3 px-2">
                                <div>
                                    <label className="text-[10px] text-slate-500">Type</label>
                                    <p className="text-xs text-white capitalize">{block.type}</p>
                                </div>
                                <div>
                                    <label className="text-[10px] text-slate-500">ID</label>
                                    <p className="text-[10px] text-slate-600 font-mono">{block.id}</p>
                                </div>
                                <Button size="sm" variant="danger" className="w-full text-xs"
                                    onClick={() => removeBlock(block.id)}>
                                    <Trash2 className="w-3 h-3 mr-1" /> Remove
                                </Button>
                            </div>
                        )
                    })()}
                </div>
            )}
        </div>
    )
}
