import React, { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { getDirectusClient, readItems } from '@/lib/directus/client';
import VisualBlockEditor from '@/components/blocks/VisualBlockEditor';
import { ContentLibrary } from './ContentLibrary';
import { Button } from '@/components/ui/button';
import { Save, Eye, Settings } from 'lucide-react';

interface EnhancedPageBuilderProps {
    pageId?: string;
    siteId: string;
    onSave?: (blocks: any[]) => void;
}

export function EnhancedPageBuilder({ pageId, siteId, onSave }: EnhancedPageBuilderProps) {
    const [blocks, setBlocks] = useState<any[]>([]);
    const [selectedAvatar, setSelectedAvatar] = useState<any>(null);
    const [showPreview, setShowPreview] = useState(false);

    // Load existing page if editing
    const { data: existingPage } = useQuery({
        queryKey: ['page', pageId],
        queryFn: async () => {
            if (!pageId) return null;
            const client = getDirectusClient();
            return await client.request(readItems('pages', {
                filter: { id: { _eq: pageId } },
                fields: ['*']
            }));
        },
        enabled: !!pageId
    });

    const handleSave = async () => {
        const client = getDirectusClient();

        const pageData = {
            site_id: siteId,
            blocks: JSON.stringify(blocks),
            status: 'draft'
        };

        if (pageId) {
            // Update existing
            await client.request({
                type: 'updateItem',
                collection: 'pages',
                id: pageId,
                data: pageData
            });
        } else {
            // Create new
            await client.request({
                type: 'createItem',
                collection: 'pages',
                data: pageData
            });
        }

        onSave?.(blocks);
    };

    const handleSelectBlock = (blockType: string, config?: any) => {
        const newBlock = {
            id: `block-${Date.now()}`,
            type: blockType,
            config: config || {}
        };
        setBlocks([...blocks, newBlock]);
    };

    const handleSelectAvatar = (avatar: any) => {
        setSelectedAvatar(avatar);
    };

    return (
        <div className="h-screen flex flex-col bg-zinc-950">
            {/* Top toolbar */}
            <div className="flex items-center justify-between px-6 py-3 bg-zinc-900 border-b border-zinc-800">
                <h1 className="text-xl font-bold text-white">Visual Page Builder</h1>

                <div className="flex items-center gap-3">
                    <Button
                        variant="outline"
                        size="sm"
                        onClick={() => setShowPreview(!showPreview)}
                        className="bg-zinc-800 border-zinc-700"
                    >
                        <Eye className="h-4 w-4 mr-2" />
                        {showPreview ? 'Edit' : 'Preview'}
                    </Button>

                    <Button
                        onClick={handleSave}
                        className="bg-green-600 hover:bg-green-700"
                    >
                        <Save className="h-4 w-4 mr-2" />
                        Save Page
                    </Button>
                </div>
            </div>

            {/* Main builder area */}
            <div className="flex-1 flex overflow-hidden">
                {/* Left: Content Library */}
                <div className="w-80 border-r border-zinc-800 overflow-y-auto">
                    <ContentLibrary
                        onSelectBlock={handleSelectBlock}
                        onSelectAvatar={handleSelectAvatar}
                    />
                </div>

                {/* Center: Visual Editor */}
                <div className="flex-1 overflow-auto">
                    {showPreview ? (
                        <div className="p-8">
                            <div className="max-w-4xl mx-auto bg-white rounded-lg shadow-xl min-h-screen p-8">
                                {/* Preview of blocks */}
                                <div className="prose">
                                    <h1>Page Preview</h1>
                                    <p>Blocks: {blocks.length}</p>
                                    {blocks.map(block => (
                                        <div key={block.id} className="border p-4 mb-4">
                                            <strong>{block.type}</strong>
                                        </div>
                                    ))}
                                </div>
                            </div>
                        </div>
                    ) : (
                        <VisualBlockEditor />
                    )}
                </div>

                {/* Right: Settings */}
                <div className="w-80 border-l border-zinc-800 bg-zinc-900 p-4">
                    <div className="flex items-center gap-2 mb-4">
                        <Settings className="h-5 w-5 text-zinc-400" />
                        <h2 className="font-semibold text-white">Settings</h2>
                    </div>

                    {selectedAvatar && (
                        <div className="p-3 bg-zinc-800 rounded-lg border border-zinc-700 mb-4">
                            <div className="text-sm font-medium text-white mb-1">Active Avatar</div>
                            <div className="text-xs text-zinc-400">{selectedAvatar.persona_name}</div>
                        </div>
                    )}

                    <div className="text-sm text-zinc-500">
                        <div className="mb-2">Blocks: {blocks.length}</div>
                        <div>Site ID: {siteId}</div>
                    </div>
                </div>
            </div>
        </div>
    );
}
