import React, { useState, useRef, useEffect, useLayoutEffect, useCallback } from 'react';
import { createPortal } from 'react-dom';
import { useNavigate } from 'react-router-dom';
import { Menu, LogOut, Cloud, Server, Lock, HelpCircle, KeyRound, Plug } from 'lucide-react';
import { useRuntime } from '@nexuscrm/host-sdk';
import { useApp } from '@nexuscrm/host-sdk';
import { hostApps } from '@nexuscrm/host-sdk';
import { NotificationCenter } from './NotificationCenter';
import { AppLauncher } from './AppLauncher';
import { useVersionCheck } from '../../core/hooks/useVersionCheck';
import { SelfChangePasswordModal } from '../auth/SelfChangePasswordModal';
import { resolveAppLaunchDestination } from '../../core/navigation/appLaunch';

interface TopBarProps {
    mobileMenuOpen: boolean;
    setMobileMenuOpen: (open: boolean) => void;
    isSidebarCollapsed: boolean;
}

export const TopBar: React.FC<TopBarProps> = ({
    mobileMenuOpen,
    setMobileMenuOpen,
    isSidebarCollapsed,
}) => {
    const { user, logout, usesExternalIdentitySession } = useRuntime();
    const { currentAppId, currentFrontendAppId, visibleApps, setCurrentAppId, loading: appsLoading } = useApp();
    const { currentVersion, buildDate } = useVersionCheck();
    const navigate = useNavigate();
    const TopBarSearch = hostApps.apps.get(currentFrontendAppId)?.shellComponents?.topBarSearch;
    const [userMenuOpen, setUserMenuOpen] = useState(false);
    const [changePasswordOpen, setChangePasswordOpen] = useState(false);
    const userMenuButtonRef = useRef<HTMLButtonElement>(null);
    const userMenuDropdownRef = useRef<HTMLDivElement>(null);
    const [menuPos, setMenuPos] = useState({ top: 0, right: 0 });

    // Position menu below avatar button
    const updateMenuPosition = useCallback(() => {
        if (userMenuButtonRef.current && userMenuOpen) {
            const rect = userMenuButtonRef.current.getBoundingClientRect();
            setMenuPos({
                top: rect.bottom + 8,
                right: window.innerWidth - rect.right,
            });
        }
    }, [userMenuOpen]);

    useLayoutEffect(() => {
        if (userMenuOpen) {
            updateMenuPosition();
            window.addEventListener('resize', updateMenuPosition);
            window.addEventListener('scroll', updateMenuPosition, true);
        }
        return () => {
            window.removeEventListener('resize', updateMenuPosition);
            window.removeEventListener('scroll', updateMenuPosition, true);
        };
    }, [userMenuOpen, updateMenuPosition]);

    // Close menu on outside click
    useEffect(() => {
        const handleClickOutside = (event: MouseEvent) => {
            if (
                userMenuDropdownRef.current && !userMenuDropdownRef.current.contains(event.target as Node) &&
                userMenuButtonRef.current && !userMenuButtonRef.current.contains(event.target as Node)
            ) {
                setUserMenuOpen(false);
            }
        };

        if (userMenuOpen) {
            document.addEventListener('mousedown', handleClickOutside);
        }

        return () => {
            document.removeEventListener('mousedown', handleClickOutside);
        };
    }, [userMenuOpen]);

    const handleLogout = () => {
        logout();
        setUserMenuOpen(false);
    };

    const getUserInitials = () => {
        if (!user?.Name) return 'U';
        const parts = user.Name.split(' ');
        if (parts.length >= 2) {
            return `${parts[0][0]}${parts[1][0]}`.toUpperCase();
        }
        return user.Name[0].toUpperCase();
    };

    const userMenuContent = (
        <div
            ref={userMenuDropdownRef}
            className="fixed w-56 bg-white border border-slate-200 rounded-lg shadow-xl py-1 z-[9999]"
            style={{ top: menuPos.top, right: menuPos.right }}
        >
            <div className="px-4 py-3 border-b border-slate-100">
                <p className="text-sm font-semibold text-slate-900">{user?.Name || 'User'}</p>
                {user?.Email && (
                    <p className="text-xs text-slate-500 mt-0.5">{user.Email}</p>
                )}
            </div>

            <div className="py-1 border-b border-slate-100">
                <p className="px-4 pt-1 pb-1.5 text-[11px] font-semibold uppercase tracking-wide text-slate-400">
                    AI &amp; integrations
                </p>
                <button
                    onClick={() => { navigate('/settings/connections'); setUserMenuOpen(false); }}
                    className="w-full px-4 py-2 text-left text-sm text-slate-700 hover:bg-slate-50 flex items-center gap-2 transition-colors"
                >
                    <Plug size={16} />
                    <span>Connected apps</span>
                </button>
                <button
                    onClick={() => { navigate('/settings/api-tokens'); setUserMenuOpen(false); }}
                    className="w-full px-4 py-2 text-left text-sm text-slate-700 hover:bg-slate-50 flex items-center gap-2 transition-colors"
                >
                    <KeyRound size={16} />
                    <span>API tokens</span>
                </button>
                <button
                    onClick={() => { navigate('/help/ai-integration'); setUserMenuOpen(false); }}
                    className="w-full px-4 py-2 text-left text-sm text-slate-700 hover:bg-slate-50 flex items-center gap-2 transition-colors"
                >
                    <HelpCircle size={16} />
                    <span>Connect an AI assistant</span>
                </button>
            </div>

            {!usesExternalIdentitySession && (
                <button
                    onClick={() => { setChangePasswordOpen(true); setUserMenuOpen(false); }}
                    className="w-full px-4 py-2 text-left text-sm text-slate-700 hover:bg-slate-50 flex items-center gap-2 transition-colors"
                >
                    <Lock size={16} />
                    <span>Change Password</span>
                </button>
            )}

            <button
                onClick={handleLogout}
                className="w-full px-4 py-2 text-left text-sm text-slate-700 hover:bg-slate-50 flex items-center gap-2 transition-colors"
            >
                <LogOut size={16} />
                <span>Logout</span>
            </button>
        </div>
    );

    return (
        <header className="h-16 bg-white border-b border-slate-200 shadow-sm z-50 flex items-center justify-between px-2 sm:px-4 shrink-0 min-w-0 relative">
            <div className="flex items-center gap-2 sm:gap-4 min-w-0 shrink-0">
                <div className="flex items-center gap-3">
                    {/* Mobile Menu Toggle */}
                    <button
                        onClick={() => setMobileMenuOpen(!mobileMenuOpen)}
                        data-testid="mobile-menu-toggle"
                        className="lg:hidden p-2 -ml-2 text-slate-500 hover:bg-slate-100 rounded-lg transition-colors"
                    >
                        <Menu size={24} />
                    </button>

                    {/* Logo */}
                    <div className={`font-bold text-xl text-slate-800 tracking-tight flex items-center gap-2 ${isSidebarCollapsed ? '' : 'lg:w-52'}`}>
                        <div className="w-8 h-8 rounded-lg flex items-center justify-center text-white" style={{ backgroundColor: 'var(--color-brand)' }}>
                            <span className="font-bold text-lg">N</span>
                        </div>
                        <span className="hidden sm:inline">NexusCRM</span>
                    </div>
                </div>

                {/* App Launcher */}
                {!appsLoading && (
                    <AppLauncher
                        currentAppId={currentAppId}
                        onSelectApp={(appId) => {
                            const selectedApp = visibleApps.find(app => app.id === appId) ?? null;
                            setCurrentAppId(appId);
                            const destination = resolveAppLaunchDestination(selectedApp, currentFrontendAppId);
                            if (destination?.kind === 'document') {
                                window.open(destination.href, '_blank', 'noopener,noreferrer');
                            } else {
                                navigate(destination?.href ?? '/');
                            }
                        }}
                    />
                )}
            </div>

            <div className="flex items-center gap-3 flex-1 max-w-2xl mx-2 sm:mx-4 min-w-0">
                {TopBarSearch && <TopBarSearch />}
            </div>

            <div className="flex items-center gap-3">
                {/* Mode indicator — shows which backend is active */}
                <div
                    title={usesExternalIdentitySession ? 'External identity session' : 'Backend session'}
                    className={`hidden sm:inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-semibold select-none ${usesExternalIdentitySession
                        ? 'bg-amber-50 text-amber-700 border border-amber-200'
                        : 'bg-blue-50 text-blue-700 border border-blue-200'
                        }`}
                >
                    {usesExternalIdentitySession
                        ? <><Cloud size={12} className="shrink-0" /><span>External</span></>
                        : <><Server size={12} className="shrink-0" /><span>Backend</span></>}
                </div>

                {/* Version badge */}
                {currentVersion && (
                    <div
                        title={`Build: ${currentVersion}${buildDate ? ' (' + new Date(buildDate).toLocaleString() + ')' : ''}`}
                        className="hidden sm:inline-flex items-center px-2 py-1 rounded-full text-[10px] font-mono text-slate-400 bg-slate-50 border border-slate-200 select-none"
                    >
                        v{currentVersion.slice(0, 8)}
                    </div>
                )}

                <button
                    onClick={() => navigate('/help/ai-integration')}
                    className="p-2 text-slate-500 hover:bg-slate-100 rounded-full transition-colors"
                    aria-label="Help & AI Tools"
                    title="Help & AI Tools"
                >
                    <HelpCircle size={20} />
                </button>

                <NotificationCenter />

                <div className="relative">
                    <button
                        ref={userMenuButtonRef}
                        onClick={() => setUserMenuOpen(!userMenuOpen)}
                        className="w-9 h-9 bg-slate-200 rounded-full flex items-center justify-center text-slate-600 font-medium hover:ring-2 hover:ring-offset-2 hover:ring-blue-500 transition-all"
                        aria-label="User menu"
                    >
                        {getUserInitials()}
                    </button>
                    {userMenuOpen && createPortal(userMenuContent, document.body)}
                </div>
            </div>
            <SelfChangePasswordModal isOpen={changePasswordOpen} onClose={() => setChangePasswordOpen(false)} />
        </header>
    );
};
