"use client";

import React, { useState, useRef, useEffect } from 'react';
import * as DropdownMenu from '@radix-ui/react-dropdown-menu';
import * as Dialog from '@radix-ui/react-dialog';
import { Book, MoreVertical, AlertTriangle } from 'lucide-react';
import { useFlowStoreActions } from '@/stores/flow-store';
import { useTemplateStore } from '@/stores/template-store';
import { useDesignStore } from '@/stores/design-store';
import { useSidebarStore } from '@/stores/sidebar-store';
import useFlowStore from '@/stores/flow-store';
import AboutStudioModal from '@/modals/about-studio';
import PromptModal from '@/modals/prompt-modal';
import SaveTemplateModal from '@/modals/save-template-modal';
import { generateAIPrompt, generateMermaidDiagram } from '@/utils/prompt-generator';

const NavigationBar = () => {
    const [isEditingName, setIsEditingName] = useState(false);
    const [tempName, setTempName] = useState('');
    const [showResetWarning, setShowResetWarning] = useState(false);
    const [showAboutModal, setShowAboutModal] = useState(false);
    const [showPromptModal, setShowPromptModal] = useState(false);
    const [showSaveTemplateModal, setShowSaveTemplateModal] = useState(false);
    const [generatedPrompt, setGeneratedPrompt] = useState('');
    const inputRef = useRef<HTMLInputElement>(null);
    const { reset, exportFlow, importFlow, autoLayout, undo, redo, canUndo, canRedo, onNodesChange } = useFlowStoreActions();
    const { setShowTemplateSelector, hasTemplates } = useTemplateStore();
    const { currentDesign, updateDesignName, createNewDesign, setCurrentDesign } = useDesignStore();
    const { showMinimap, toggleMinimap, showComments, toggleComments, toggleFeedbackPanel } = useSidebarStore();
    const { nodes } = useFlowStore();


    const handleResetClick = () => {
        setShowResetWarning(true);
    };

    const handleConfirmReset = () => {
        reset();
        setShowResetWarning(false);
    };

    const handleCancelReset = () => {
        setShowResetWarning(false);
    };

    const handleSelectAll = () => {
        // Select all nodes
        const nodeUpdates = nodes.map(node => ({
            id: node.id,
            type: 'select' as const,
            selected: true
        }));
        onNodesChange(nodeUpdates);
    };

    const startEditing = () => {
        setTempName(currentDesign?.name || '');
        setIsEditingName(true);
    };

    const saveNameChange = () => {
        if (currentDesign && tempName.trim() && tempName !== currentDesign.name) {
            updateDesignName(currentDesign.id, tempName.trim());
        }
        setIsEditingName(false);
    };

    const cancelEditing = () => {
        setTempName('');
        setIsEditingName(false);
    };

    const handleKeyDown = (e: React.KeyboardEvent) => {
        if (e.key === 'Enter') {
            saveNameChange();
        } else if (e.key === 'Escape') {
            cancelEditing();
        }
    };

    // Focus input when editing starts
    useEffect(() => {
        if (isEditingName && inputRef.current) {
            inputRef.current.focus();
            inputRef.current.select();
        }
    }, [isEditingName]);

    const saveToFile = () => {
        const data = exportFlow();

        // Check if the browser supports the File System Access API
        if ('showSaveFilePicker' in window) {
            // Modern browsers with File System Access API
            const saveFileWithPicker = async () => {
                try {
                    const fileHandle = await (window as any).showSaveFilePicker({
                        suggestedName: `${currentDesign?.name || 'design'}.ecstudio`,
                        types: [{
                            description: 'EventCatalog Studio files',
                            accept: { 'application/json': ['.ecstudio'] }
                        }]
                    });

                    const writable = await fileHandle.createWritable();
                    await writable.write(JSON.stringify(data, null, 2));
                    await writable.close();
                } catch (error) {
                    // User cancelled or other error
                    if (error instanceof Error && error.name !== 'AbortError') {
                        console.error('Error saving file:', error);
                    }
                }
            };
            saveFileWithPicker();
        } else {
            // Fallback for browsers without File System Access API
            const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `${currentDesign?.name || 'design'}.ecstudio`;
            a.click();
            URL.revokeObjectURL(url);
        }
    }

    const openFromFile = () => {
        const fileInput = document.createElement('input');
        fileInput.type = 'file';
        fileInput.accept = '.ecstudio';
        fileInput.onchange = (e) => {
            const target = e.target as HTMLInputElement;
            const file = target?.files?.[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = (event) => {
                    try {
                        const data = JSON.parse(event.target?.result as string);
                        importFlow(data);
                        // Update the current design name based on metadata (root level or nested) or filename
                        const designName = data.name || data.metadata?.name || file.name.replace('.ecstudio', '');
                        if (currentDesign?.id) {
                            updateDesignName(currentDesign.id, designName);
                        }
                    } catch (error) {
                        console.error('Error parsing file:', error);
                        alert('Error: Invalid file format. Please select a valid .ecstudio file.');
                    }
                }
                reader.readAsText(file);
            }
        }
        fileInput.click();
    }

    const handleGeneratePrompt = () => {
        const flowData = exportFlow();
        const designName = currentDesign?.name || 'Untitled Design';
        
        if (!flowData) {
            throw new Error('Unable to export flow data');
        }
        
        return generateAIPrompt({ flowData, designName });
    }

    const exportToPrompt = () => {
        try {
            const prompt = handleGeneratePrompt();
            if (prompt) {
                setGeneratedPrompt(prompt);
                setShowPromptModal(true);
            }
        } catch (error) {
            console.error('Error generating prompt:', error);
            alert(error instanceof Error ? error.message : 'Error generating prompt. Please try again.');
        }
    }

    const saveAsTemplate = (templateData: {
        title: string;
        description: string;
        tags: string[];
    }) => {
        const flowData = exportFlow();
        if (!flowData) {
            alert('Unable to export flow data. Please try again.');
            return;
        }

        const mermaidDiagram = generateMermaidDiagram(flowData);
        
        const template = {
            title: templateData.title,
            description: templateData.description,
            type: 'custom',
            data: flowData,
            usecase: templateData.description,
            mermaid: mermaidDiagram,
            tags: templateData.tags
        };

        const blob = new Blob([JSON.stringify(template, null, 2)], { type: 'application/json' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `${templateData.title.toLowerCase().replace(/[^a-z0-9]/g, '-')}.ectemplate`;
        a.click();
        URL.revokeObjectURL(url);
    }

    const handleNewDesign = () => {
        if (hasTemplates()) {
            // If templates are available, show the template selector
            setShowTemplateSelector(true);
        } else {
            // If no templates, create a blank design directly
            const newDesign = {
                id: Math.random().toString(36).substring(2, 15),
                type: 'design',
                name: 'Untitled Design',
                description: '',
                data: {
                    nodes: [],
                    edges: [],
                    viewport: { x: 0, y: 0, zoom: 1 }
                },
                createdAt: new Date(),
                updatedAt: new Date(),
                lastModified: 'now'
            };
            createNewDesign(newDesign);
            setCurrentDesign(newDesign);
        }
    }


    return (
        <div className="bg-white px-3 py-2 flex items-center justify-between w-full border-b border-gray-200">
            {/* Left: Book Icon + Three Dots Menu */}
            <div className="flex items-center">
                <Book className="h-5 w-5 text-gray-700 flex-shrink-0 mr-1" />
                <DropdownMenu.Root>
                <DropdownMenu.Trigger asChild>
                    <button className="p-1 rounded hover:bg-gray-100 transition-colors flex-shrink-0">
                        <MoreVertical className="h-5 w-5 text-gray-700" />
                    </button>
                </DropdownMenu.Trigger>
                <DropdownMenu.Portal>
                    <DropdownMenu.Content 
                        className="bg-white rounded-lg shadow-lg border border-gray-200 p-1 w-48 z-50 ml-12"
                        align="end"
                        sideOffset={5}
                    >
                        {/* File operations - most common actions first */}
                        <DropdownMenu.Item 
                            onClick={handleNewDesign}
                            className="flex items-center justify-between px-3 py-2 text-sm rounded hover:bg-gray-100 cursor-default outline-none"
                        >
                            <span>New Design</span>
                            <span className="text-xs text-gray-500">^ N</span>
                        </DropdownMenu.Item>
                        <DropdownMenu.Item 
                            onClick={() => openFromFile()}
                            className="flex items-center justify-between px-3 py-2 text-sm rounded hover:bg-gray-100 cursor-default outline-none"
                        >
                            <span>Open</span>
                            <span className="text-xs text-gray-500">⌘ O</span>
                        </DropdownMenu.Item>
                        <DropdownMenu.Item 
                            onClick={() => saveToFile()}
                            className="flex items-center justify-between px-3 py-2 text-sm rounded hover:bg-gray-100 cursor-default outline-none"
                        >
                            <span>Save</span>
                            <span className="text-xs text-gray-500">⌘ S</span>
                        </DropdownMenu.Item>
                    

                        <DropdownMenu.Separator className="h-px bg-gray-200 my-1" />

                        {/* Export submenu */}
                        <DropdownMenu.Sub>
                            <DropdownMenu.SubTrigger className="flex items-center justify-between px-3 py-2 text-sm rounded hover:bg-gray-100 cursor-default outline-none">
                                <span>Export</span>
                                <span className="text-xs text-gray-500">›</span>
                            </DropdownMenu.SubTrigger>
                            <DropdownMenu.Portal>
                                <DropdownMenu.SubContent 
                                    className="bg-white rounded-lg shadow-lg border border-gray-200 p-1 w-56 z-50"
                                    sideOffset={5}
                                >
                                    <DropdownMenu.Item 
                                        onClick={exportToPrompt}
                                        className="flex items-center px-3 py-2 text-sm rounded hover:bg-gray-100 cursor-default outline-none whitespace-nowrap"
                                    >
                                        <span>as LLM prompt</span>
                                    </DropdownMenu.Item>
                                    <DropdownMenu.Item 
                                        onClick={() => setShowSaveTemplateModal(true)}
                                        className="flex items-center px-3 py-2 text-sm rounded hover:bg-gray-100 cursor-default outline-none whitespace-nowrap"
                                    >
                                        <span>as Template</span>
                                    </DropdownMenu.Item>
                                </DropdownMenu.SubContent>
                            </DropdownMenu.Portal>
                        </DropdownMenu.Sub>

                        <DropdownMenu.Separator className="h-px bg-gray-200 my-1" />

                        {/* Edit actions */}
                        <DropdownMenu.Item 
                            onClick={undo}
                            disabled={!canUndo()}
                            className={`flex items-center justify-between px-3 py-2 text-sm rounded outline-none cursor-default ${
                                canUndo() ? 'hover:bg-gray-100' : 'text-gray-400 cursor-not-allowed'
                            }`}
                        >
                            <span>Undo</span>
                            <span className="text-xs text-gray-500">⌘Z</span>
                        </DropdownMenu.Item>
                        <DropdownMenu.Item 
                            onClick={redo}
                            disabled={!canRedo()}
                            className={`flex items-center justify-between px-3 py-2 text-sm rounded outline-none cursor-default ${
                                canRedo() ? 'hover:bg-gray-100' : 'text-gray-400 cursor-not-allowed'
                            }`}
                        >
                            <span>Redo</span>
                            <span className="text-xs text-gray-500">⇧⌘Z</span>
                        </DropdownMenu.Item>
                        <DropdownMenu.Item 
                            onClick={handleSelectAll}
                            className="flex items-center justify-between px-3 py-2 text-sm rounded hover:bg-gray-100 cursor-default outline-none"
                        >
                            <span>Select All</span>
                            <span className="text-xs text-gray-500">⌘A</span>
                        </DropdownMenu.Item>

                        <DropdownMenu.Separator className="h-px bg-gray-200 my-1" />

                        {/* View actions */}
                        <DropdownMenu.CheckboxItem 
                            checked={showMinimap}
                            onCheckedChange={toggleMinimap}
                            className="flex items-center justify-between px-3 py-2 text-sm rounded hover:bg-gray-100 cursor-default outline-none"
                        >
                            <span>Show Minimap</span>
                            {showMinimap && <span className="text-blue-600">✓</span>}
                        </DropdownMenu.CheckboxItem>
                        <DropdownMenu.CheckboxItem 
                            checked={showComments}
                            onCheckedChange={toggleComments}
                            className="flex items-center justify-between px-3 py-2 text-sm rounded hover:bg-gray-100 cursor-default outline-none"
                        >
                            <span>Show Comments</span>
                            {showComments && <span className="text-blue-600">✓</span>}
                        </DropdownMenu.CheckboxItem>
                        <DropdownMenu.Item 
                            onClick={autoLayout}
                            className="flex items-center px-3 py-2 text-sm rounded hover:bg-gray-100 cursor-default outline-none"
                        >
                            Auto Layout
                        </DropdownMenu.Item>

                        <DropdownMenu.Separator className="h-px bg-gray-200 my-1" />
                        
                        <DropdownMenu.Item 
                            onClick={() => setShowAboutModal(true)}
                            className="flex items-center px-3 py-2 text-sm rounded hover:bg-gray-100 cursor-default outline-none"
                        >
                            About Studio
                        </DropdownMenu.Item>
                        
                        <DropdownMenu.Separator className="h-px bg-gray-200 my-1" />
                        
                        <DropdownMenu.Item 
                            onClick={handleResetClick}
                            className="px-3 py-2 text-sm rounded hover:bg-gray-100 cursor-default outline-none text-red-600"
                        >
                            Reset Canvas
                        </DropdownMenu.Item>
                    </DropdownMenu.Content>
                </DropdownMenu.Portal>
            </DropdownMenu.Root>
            </div>

            {/* Center: Design Name */}
            <div className="flex-1 flex justify-center">
                {isEditingName ? (
                    <input
                        ref={inputRef}
                        type="text"
                        value={tempName}
                        onChange={(e) => setTempName(e.target.value)}
                        onBlur={saveNameChange}
                        onKeyDown={handleKeyDown}
                        className="font-medium text-gray-800 bg-transparent border-0 text-center focus:outline-none focus:ring-0 text-sm max-w-xs"
                    />
                ) : (
                    <button
                        onClick={startEditing}
                        className="font-medium text-gray-800 hover:text-gray-600 transition-colors text-sm"
                        title="Click to edit design name"
                    >
                        {currentDesign?.name || 'Untitled Design'}
                    </button>
                )}
            </div>

            {/* Right: Sign In Button */}
            <div className="flex items-center gap-2">
                <button className="px-3 py-1 text-sm border border-gray-300 rounded hover:bg-gray-100 text-gray-700">
                    Sign In
                </button>
            </div>

            <AboutStudioModal isOpen={showAboutModal} onClose={() => setShowAboutModal(false)} />
            <PromptModal 
                isOpen={showPromptModal} 
                onClose={() => setShowPromptModal(false)}
                prompt={generatedPrompt}
                title={`Architecture Prompt: ${currentDesign?.name || 'Untitled Design'}`}
            />
            <SaveTemplateModal 
                isOpen={showSaveTemplateModal} 
                onClose={() => setShowSaveTemplateModal(false)}
                onSave={saveAsTemplate}
            />

            {/* Reset Canvas Warning Dialog */}
            <Dialog.Root open={showResetWarning} onOpenChange={setShowResetWarning}>
                <Dialog.Portal>
                    <Dialog.Overlay className="fixed inset-0 bg-black/30 z-50" />
                    <Dialog.Content className="fixed left-1/2 top-1/2 w-full max-w-md -translate-x-1/2 -translate-y-1/2 transform rounded-lg bg-white p-6 shadow-xl z-50">
                        <div className="flex items-start space-x-3">
                            <div className="flex-shrink-0">
                                <AlertTriangle className="h-6 w-6 text-red-500" />
                            </div>
                            <div className="flex-1">
                                <Dialog.Title className="text-lg font-semibold text-gray-900 mb-2">
                                    Reset Canvas
                                </Dialog.Title>
                                <Dialog.Description className="text-sm text-gray-600 mb-4">
                                    This will remove all nodes and connections from the canvas. This action cannot be undone.
                                </Dialog.Description>
                                <div className="flex justify-end space-x-3">
                                    <button
                                        onClick={handleCancelReset}
                                        className="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition-colors"
                                    >
                                        Cancel
                                    </button>
                                    <button
                                        onClick={handleConfirmReset}
                                        className="px-4 py-2 text-sm font-medium text-white bg-red-600 border border-transparent rounded-md hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2 transition-colors"
                                    >
                                        Reset Canvas
                                    </button>
                                </div>
                            </div>
                        </div>
                    </Dialog.Content>
                </Dialog.Portal>
            </Dialog.Root>
        </div>
    );
};

export default NavigationBar;
