import React, { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { getDirectusClient, readItems } from '@/lib/directus/client';
import { Card } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Search, Blocks, Users, FileText, Layout } from 'lucide-react';

interface ContentLibraryProps {
    onSelectBlock?: (blockType: string, config?: any) => void;
    onSelectAvatar?: (avatar: any) => void;
    onSelectFragment?: (fragment: any) => void;
}

export function ContentLibrary({ onSelectBlock, onSelectAvatar, onSelectFragment }: ContentLibraryProps) {
    const [searchTerm, setSearchTerm] = useState('');

    // Fetch avatars
    const { data: avatars, isLoading: loadingAvatars } = useQuery({
        queryKey: ['avatars'],
        queryFn: async () => {
            const client = getDirectusClient();
            return await client.request(readItems('avatar_intelligence', {
                limit: 100,
                fields: ['id', 'persona_name', 'pain_points', 'desires', 'demographics']
            }));
        }
    });

    // Fetch content fragments
    const { data: fragments, isLoading: loadingFragments } = useQuery({
        queryKey: ['content_fragments'],
        queryFn: async () => {
            const client = getDirectusClient();
            return await client.request(readItems('content_fragments', {
                limit: 100,
                fields: ['id', 'name', 'type', 'content']
            }));
        }
    });

    // Fetch offer blocks
    const { data: offers, isLoading: loadingOffers } = useQuery({
        queryKey: ['offer_blocks'],
        queryFn: async () => {
            const client = getDirectusClient();
            return await client.request(readItems('offer_blocks', {
                limit: 100,
                fields: ['id', 'title', 'offer_text', 'cta_text']
            }));
        }
    });

    // Built-in block types
    const blockTypes = [
        { id: 'hero', name: 'Hero Section', icon: '🦸', description: 'Large header with headline and CTA' },
        { id: 'features', name: 'Features Grid', icon: '⚡', description: '3-column feature showcase' },
        { id: 'content', name: 'Content Block', icon: '📝', description: 'Rich text content area' },
        { id: 'cta', name: 'Call to Action', icon: '🎯', description: 'Prominent CTA button' },
        { id: 'form', name: 'Lead Form', icon: '📋', description: 'Contact/signup form' },
    ];

    const filteredAvatars = avatars?.filter(a =>
        a.persona_name?.toLowerCase().includes(searchTerm.toLowerCase())
    ) || [];

    const filteredFragments = fragments?.filter(f =>
        f.name?.toLowerCase().includes(searchTerm.toLowerCase())
    ) || [];

    return (
        <Card className="h-full flex flex-col bg-zinc-900 border-zinc-800">
            <div className="p-4 border-b border-zinc-800">
                <h2 className="text-lg font-semibold text-white mb-3">Content Library</h2>
                <div className="relative">
                    <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-zinc-500" />
                    <Input
                        placeholder="Search..."
                        value={searchTerm}
                        onChange={(e) => setSearchTerm(e.target.value)}
                        className="pl-9 bg-zinc-800 border-zinc-700 text-white"
                    />
                </div>
            </div>

            <Tabs defaultValue="blocks" className="flex-1 flex flex-col">
                <TabsList className="grid w-full grid-cols-4 bg-zinc-800 mx-4 mt-2">
                    <TabsTrigger value="blocks" className="text-xs">
                        <Blocks className="h-3 w-3 mr-1" />
                        Blocks
                    </TabsTrigger>
                    <TabsTrigger value="avatars" className="text-xs">
                        <Users className="h-3 w-3 mr-1" />
                        Avatars
                    </TabsTrigger>
                    <TabsTrigger value="fragments" className="text-xs">
                        <FileText className="h-3 w-3 mr-1" />
                        Fragments
                    </TabsTrigger>
                    <TabsTrigger value="templates" className="text-xs">
                        <Layout className="h-3 w-3 mr-1" />
                        Templates
                    </TabsTrigger>
                </TabsList>

                <div className="flex-1 overflow-y-auto p-4">
                    <TabsContent value="blocks" className="mt-0 space-y-2">
                        {blockTypes.map(block => (
                            <button
                                key={block.id}
                                onClick={() => onSelectBlock?.(block.id)}
                                className="w-full p-3 text-left bg-zinc-800 hover:bg-zinc-700 border border-zinc-700 rounded-lg transition-colors group"
                            >
                                <div className="flex items-start gap-3">
                                    <span className="text-2xl">{block.icon}</span>
                                    <div className="flex-1 min-w-0">
                                        <div className="font-medium text-white text-sm">{block.name}</div>
                                        <div className="text-xs text-zinc-400 truncate">{block.description}</div>
                                    </div>
                                </div>
                            </button>
                        ))}
                    </TabsContent>

                    <TabsContent value="avatars" className="mt-0 space-y-2">
                        {loadingAvatars ? (
                            <div className="text-center text-zinc-500 py-8">Loading avatars...</div>
                        ) : filteredAvatars.length === 0 ? (
                            <div className="text-center text-zinc-500 py-8">No avatars found</div>
                        ) : (
                            filteredAvatars.map((avatar: any) => (
                                <button
                                    key={avatar.id}
                                    onClick={() => onSelectAvatar?.(avatar)}
                                    className="w-full p-3 text-left bg-zinc-800 hover:bg-zinc-700 border border-zinc-700 rounded-lg transition-colors"
                                >
                                    <div className="font-medium text-white text-sm mb-1">{avatar.persona_name}</div>
                                    <div className="text-xs text-zinc-400 line-clamp-2">
                                        {avatar.pain_points || avatar.demographics}
                                    </div>
                                </button>
                            ))
                        )}
                    </TabsContent>

                    <TabsContent value="fragments" className="mt-0 space-y-2">
                        {loadingFragments ? (
                            <div className="text-center text-zinc-500 py-8">Loading fragments...</div>
                        ) : filteredFragments.length === 0 ? (
                            <div className="text-center text-zinc-500 py-8">No fragments found</div>
                        ) : (
                            filteredFragments.map((fragment: any) => (
                                <button
                                    key={fragment.id}
                                    onClick={() => onSelectFragment?.(fragment)}
                                    className="w-full p-3 text-left bg-zinc-800 hover:bg-zinc-700 border border-zinc-700 rounded-lg transition-colors"
                                >
                                    <div className="flex items-center justify-between mb-1">
                                        <div className="font-medium text-white text-sm">{fragment.name}</div>
                                        {fragment.type && (
                                            <span className="px-2 py-0.5 text-xs bg-blue-500/20 text-blue-400 rounded">
                                                {fragment.type}
                                            </span>
                                        )}
                                    </div>
                                    <div className="text-xs text-zinc-400 line-clamp-2">
                                        {fragment.content?.substring(0, 100)}...
                                    </div>
                                </button>
                            ))
                        )}
                    </TabsContent>

                    <TabsContent value="templates" className="mt-0 space-y-2">
                        <div className="text-sm text-zinc-400 mb-4">Pre-built page templates</div>
                        {['Landing Page', 'Squeeze Page', 'Sales Page', 'About Page'].map(template => (
                            <button
                                key={template}
                                className="w-full p-3 text-left bg-zinc-800 hover:bg-zinc-700 border border-zinc-700 rounded-lg transition-colors"
                            >
                                <div className="font-medium text-white text-sm">{template}</div>
                                <div className="text-xs text-zinc-400">Click to load template</div>
                            </button>
                        ))}
                    </TabsContent>
                </div>
            </Tabs>
        </Card>
    );
}
