import React, { useState, useMemo } from 'react';
import * as Dialog from '@radix-ui/react-dialog';
import { useTemplateStore } from '@/stores/template-store';
import { LayoutGrid, MessageSquare, Settings, FileText, Bot, Workflow, X } from 'lucide-react';
import { useDesignStore } from '@/stores/design-store';
import MermaidDiagram from '@/components/ui/mermaid-diagram';

const TemplateSelector = () => {
    const { getTemplates, showTemplateSelector, setShowTemplateSelector } = useTemplateStore();
    const templates = getTemplates();
    const { designs, setCurrentDesign, createNewDesign } = useDesignStore();
    const [selectedTags, setSelectedTags] = useState<string[]>([]);

    // Get all unique tags from templates
    const allTags = useMemo(() => {
        const tagSet = new Set<string>();
        templates.forEach(template => {
            template.tags?.forEach(tag => tagSet.add(tag));
        });
        return Array.from(tagSet).sort();
    }, [templates]);

    // Filter templates based on selected tags
    const filteredTemplates = useMemo(() => {
        if (selectedTags.length === 0) return templates;
        return templates.filter(template => 
            selectedTags.some(selectedTag => template.tags?.includes(selectedTag))
        );
    }, [templates, selectedTags]);

    if (!showTemplateSelector) {
        return null;
    }

    const toggleTag = (tag: string) => {
        setSelectedTags(prev => 
            prev.includes(tag) 
                ? prev.filter(t => t !== tag)
                : [...prev, tag]
        );
    };

    const clearAllTags = () => {
        setSelectedTags([]);
    };


    const handleSelectTemplate = (template: any) => {
        const newDesign = {
            id: Math.random().toString(36).substring(2, 15),
            name: template.title,
            description: template.description,
            type: template.type,
            data: template.data,
            createdAt: new Date(),
            updatedAt: new Date(),
            lastModified: 'now',
        }
        createNewDesign(newDesign);
        setCurrentDesign(newDesign);
        setShowTemplateSelector(false);
    }

    return (
        <Dialog.Root open={showTemplateSelector} onOpenChange={setShowTemplateSelector}>
            <Dialog.Portal>
                <Dialog.Overlay className="fixed inset-0 bg-black/30 z-10" />
                <Dialog.Content className="fixed left-1/2 top-1/2 w-full h-full max-h-[80vh] z-20 max-w-6xl -translate-x-1/2 -translate-y-1/2 transform rounded-lg bg-white text-gray-900 shadow-2xl">
                    <div className="h-full overflow-y-auto p-8">
                        {/* Header with Blank Design CTA */}
                        <div className="flex items-center justify-between mb-8">
                            <div>
                                <Dialog.Title className="text-2xl font-semibold text-gray-900">Choose a template</Dialog.Title>
                                <Dialog.Description className="mt-1 text-sm text-gray-600">
                                    Start with architecture pattern templates or create from scratch.
                                </Dialog.Description>
                            </div>
                            <button
                                onClick={() => {
                                    setShowTemplateSelector(false);
                                    const newDesign = {
                                        id: Math.random().toString(36).substring(2, 15),
                                        name: `New Design ${designs.length + 1}`,
                                        description: 'New design',
                                        type: 'blank',
                                        data: { nodes: [], edges: [], viewport: { x: 0, y: 0, zoom: 1 } },
                                        createdAt: new Date(),
                                        updatedAt: new Date(),
                                        lastModified: 'now',
                                    };
                                    createNewDesign(newDesign);
                                    setCurrentDesign(newDesign);
                                }}
                                className="inline-flex items-center rounded-md border border-transparent bg-green-600 px-4 py-2 text-sm font-medium text-white shadow-sm hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2"
                            >
                                + Blank Design
                            </button>
                        </div>

                        {/* Tag Filters */}
                        <div className="mb-6">
                            <div className="flex items-center justify-between mb-3">
                                <h3 className="text-sm font-medium text-gray-700">Filter by tags:</h3>
                                {selectedTags.length > 0 && (
                                    <button
                                        onClick={clearAllTags}
                                        className="text-xs text-gray-500 hover:text-gray-700 flex items-center"
                                    >
                                        <X className="h-3 w-3 mr-1" />
                                        Clear all
                                    </button>
                                )}
                            </div>
                            <div className="flex flex-wrap gap-2">
                                {allTags.map((tag) => (
                                    <button
                                        key={tag}
                                        onClick={() => toggleTag(tag)}
                                        className={`px-3 py-1 rounded-full text-xs font-medium transition-colors ${
                                            selectedTags.includes(tag)
                                                ? 'bg-blue-100 text-blue-700 border border-blue-200'
                                                : 'bg-gray-100 text-gray-600 hover:bg-gray-200 border border-gray-200'
                                        }`}
                                    >
                                        {tag}
                                    </button>
                                ))}
                            </div>
                            {selectedTags.length > 0 && (
                                <div className="mt-2 text-xs text-gray-500">
                                    Showing {filteredTemplates.length} of {templates.length} templates
                                </div>
                            )}
                        </div>

                        {/* Templates Grid */}
                        <div className="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
                                {filteredTemplates.map((template) => {
                                    const getTemplateIcon = () => {
                                        if (template.title.includes('Service')) return <Settings className="h-6 w-6" />;
                                        if (template.title.includes('Business Workflow')) return <Workflow className="h-6 w-6" />;
                                        if (template.title.includes('Payment')) return <Briefcase className="h-6 w-6" />;
                                        if (template.title.includes('E-commerce') || template.title.includes('Checkout')) return <Bot className="h-6 w-6" />;
                                        if (template.title.includes('Banking')) return <FileText className="h-6 w-6" />;
                                        if (template.title.includes('Subscription')) return <MessageSquare className="h-6 w-6" />;
                                        return <LayoutGrid className="h-6 w-6" />;
                                    };
                                    
                                    return (
                                        <div key={template.title} className="group relative rounded-lg border border-gray-200 bg-white p-6 shadow-sm transition-all hover:shadow-md hover:border-gray-300 flex flex-col">
                                            {/* Diagram Section */}
                                            <div className="mb-4 h-24 bg-gray-50 rounded-md border border-gray-100 flex items-center justify-center">
                                                {template.mermaid ? (
                                                    <MermaidDiagram 
                                                        chart={template.mermaid} 
                                                        className="w-full h-full p-2"
                                                    />
                                                ) : (
                                                    <span className="text-gray-400 text-xs">No preview</span>
                                                )}
                                            </div>
                                            
                                            {/* Content Section */}
                                            <div className="flex-1 flex flex-col">
                                                <h3 className="text-lg font-semibold text-gray-900">{template.title}</h3>
                                                <p className="mt-2 text-sm text-gray-600 flex-1">{template.description}</p>
                                                
                                                {/* Tags */}
                                                {template.tags && template.tags.length > 0 && (
                                                    <div className="mt-3 flex flex-wrap gap-1">
                                                        {template.tags.slice(0, 3).map((tag) => (
                                                            <span
                                                                key={tag}
                                                                className="px-2 py-1 text-xs bg-gray-100 text-gray-600 rounded-md"
                                                            >
                                                                {tag}
                                                            </span>
                                                        ))}
                                                        {template.tags.length > 3 && (
                                                            <span className="px-2 py-1 text-xs text-gray-500">
                                                                +{template.tags.length - 3}
                                                            </span>
                                                        )}
                                                    </div>
                                                )}
                                                
                                                {/* Button at bottom */}
                                                <button
                                                    onClick={() => handleSelectTemplate(template)}
                                                    className="mt-4 w-full rounded-md bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition-colors"
                                                >
                                                    Use template
                                                </button>
                                            </div>
                                        </div>
                                    );
                                })}
                        </div>
                    </div>
                    <Dialog.Close asChild>
                        <button
                            className="absolute right-4 top-4 rounded-full p-1 text-gray-500 hover:bg-gray-100 hover:text-gray-700 focus:outline-none focus:ring-2 focus:ring-gray-400"
                            aria-label="Close"
                        >
                            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="h-6 w-6">
                                <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
                            </svg>
                        </button>
                    </Dialog.Close>
                </Dialog.Content>
            </Dialog.Portal>
        </Dialog.Root>
    );
};

export default TemplateSelector;