import React, { useState, useRef, useEffect } from 'react';
import { createPortal } from 'react-dom';
import { Link } from 'react-router-dom';
import * as Icons from 'lucide-react';
import { Grid3X3, ChevronDown, Check } from 'lucide-react';
import { useApp } from '@nexuscrm/host-sdk';
import { tryGetSetupBasePath, tryGetSetupCapabilityPagePath } from '../../core/navigation/setupPagePaths';
import { lucideIconComponent, type LucideIconComponent } from '../../core/icons/lucideIconComponents';

interface AppLauncherProps {
    currentAppId: string | null;
    onSelectApp: (appId: string) => void;
}

export const AppLauncher: React.FC<AppLauncherProps> = ({ currentAppId, onSelectApp }) => {
    const [isOpen, setIsOpen] = useState(false);
    const [searchTerm, setSearchTerm] = useState('');
    const { visibleApps, loading, currentFrontendAppId } = useApp();
    const buttonRef = useRef<HTMLButtonElement>(null);
    const dropdownRef = useRef<HTMLDivElement>(null);
    const [dropdownPos, setDropdownPos] = useState({ top: 0, left: 0 });

    const updatePosition = React.useCallback(() => {
        if (buttonRef.current && isOpen) {
            const rect = buttonRef.current.getBoundingClientRect();
            // Position: Left aligned, below button, with slight gap
            setDropdownPos({
                top: rect.bottom + 8,
                left: rect.left
            });
        }
    }, [isOpen]);

    React.useLayoutEffect(() => {
        if (isOpen) {
            updatePosition();
            // Update on resize/scroll
            window.addEventListener('resize', updatePosition);
            window.addEventListener('scroll', updatePosition, true);
        }
        return () => {
            window.removeEventListener('resize', updatePosition);
            window.removeEventListener('scroll', updatePosition, true);
        };
    }, [isOpen, updatePosition]);

    useEffect(() => {
        const handleClickOutside = (event: MouseEvent) => {
            if (
                dropdownRef.current &&
                !dropdownRef.current.contains(event.target as Node) &&
                buttonRef.current &&
                !buttonRef.current.contains(event.target as Node)
            ) {
                setIsOpen(false);
                setSearchTerm('');
            }
        };

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

    const currentApp = visibleApps.find(app => app.id === currentAppId);
    const setupBasePath = tryGetSetupBasePath(currentFrontendAppId);
    const objectManagerPath = tryGetSetupCapabilityPagePath(currentFrontendAppId, 'objectManager');
    const appsPath = tryGetSetupCapabilityPagePath(currentFrontendAppId, 'appManager');
    const hasQuickLinks = Boolean(setupBasePath || objectManagerPath || appsPath);

    const filteredApps = searchTerm
        ? visibleApps.filter(app => app.label.toLowerCase().includes(searchTerm.toLowerCase()))
        : visibleApps;

    const getIconComponent = (iconName: string): LucideIconComponent =>
        lucideIconComponent(iconName) ?? (Icons.Layers as unknown as LucideIconComponent);

    const dropdownContent = (
        <div
            ref={dropdownRef}
            className="fixed w-80 bg-white/95 backdrop-blur-xl border border-slate-200/80 rounded-xl shadow-2xl z-[9999]"
            style={{
                top: dropdownPos.top,
                left: dropdownPos.left
            }}
        >
            <div className="p-3 border-b border-slate-100">
                <h3 className="text-sm font-semibold text-slate-700">App Launcher</h3>
                <p className="text-xs text-slate-500 mt-0.5">Switch between applications</p>
            </div>

            {/* Search Input */}
            {visibleApps.length > 0 && (
                <div className="px-3 pt-2">
                    <div className="relative">
                        <Icons.Search size={14} className="absolute left-2.5 top-1/2 -translate-y-1/2 text-slate-400" />
                        <input
                            type="text"
                            value={searchTerm}
                            onChange={(e) => setSearchTerm(e.target.value)}
                            placeholder="Search apps..."
                            autoFocus
                            className="w-full pl-8 pr-3 py-1.5 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent placeholder-slate-400"
                        />
                    </div>
                </div>
            )}

            <div className="p-2 max-h-80 overflow-y-auto">
                {loading ? (
                    <div className="p-4 text-center text-slate-500 text-sm">Loading apps...</div>
                ) : visibleApps.length === 0 ? (
                    <div className="p-3 space-y-3">
                        <p className="text-xs text-slate-500 text-center">No apps created yet</p>

                        {hasQuickLinks && (
                            <div className="space-y-1">
                                <p className="text-xs font-semibold text-slate-600 uppercase tracking-wide">Quick Links</p>
                                {setupBasePath && (
                                    <Link
                                        to={setupBasePath}
                                        onClick={() => setIsOpen(false)}
                                        className="flex items-center gap-2 px-3 py-2 rounded-lg hover:bg-slate-50 transition-colors"
                                    >
                                        <Icons.Settings size={16} className="text-slate-500" />
                                        <span className="text-sm text-slate-700">Setup</span>
                                    </Link>
                                )}
                                {objectManagerPath && (
                                    <Link
                                        to={objectManagerPath}
                                        onClick={() => setIsOpen(false)}
                                        className="flex items-center gap-2 px-3 py-2 rounded-lg hover:bg-slate-50 transition-colors"
                                    >
                                        <Icons.Database size={16} className="text-slate-500" />
                                        <span className="text-sm text-slate-700">Object Manager</span>
                                    </Link>
                                )}
                            </div>
                        )}

                        {/* Create App CTA */}
                        {appsPath && (
                            <Link
                                to={appsPath}
                                onClick={() => setIsOpen(false)}
                                className="flex items-center justify-center gap-2 w-full px-3 py-2 bg-blue-50 text-blue-600 rounded-lg hover:bg-blue-100 transition-colors"
                            >
                                <Icons.Plus size={16} />
                                <span className="text-sm font-medium">Create Your First App</span>
                            </Link>
                        )}
                    </div>
                ) : filteredApps.length === 0 ? (
                    <div className="p-4 text-center text-slate-500 text-sm">No apps match &ldquo;{searchTerm}&rdquo;</div>
                ) : (
                    <div className="grid grid-cols-3 gap-2">
                        {filteredApps.map(app => {
                            const IconComponent = getIconComponent(app.icon || '');
                            const isSelected = app.id === currentAppId;
                            return (
                                <button
                                    key={app.id}
                                    onClick={() => {
                                        onSelectApp(app.id);
                                        setIsOpen(false);
                                        setSearchTerm('');
                                    }}
                                    className={`flex flex-col items-center p-3 rounded-lg transition-colors relative
                ${isSelected
                                            ? 'bg-blue-50 ring-2 ring-blue-500'
                                            : 'hover:bg-slate-50'
                                        }`}
                                >
                                    {isSelected && (
                                        <div className="absolute top-1 right-1">
                                            <Check size={12} className="text-blue-600" />
                                        </div>
                                    )}
                                    <div className={`w-10 h-10 rounded-lg flex items-center justify-center mb-1.5 shrink-0
                ${isSelected ? 'bg-blue-100 text-blue-600' : 'bg-slate-100 text-slate-600'}`}
                                    >
                                        <IconComponent size={20} />
                                    </div>
                                    <span className={`text-xs font-medium text-center line-clamp-2 break-words w-full leading-tight
                ${isSelected ? 'text-blue-700' : 'text-slate-700'}`}>
                                        {app.label}
                                    </span>
                                </button>
                            );
                        })}
                    </div>
                )}
            </div>

            {appsPath && (
                <div className="p-2 border-t border-slate-100">
                    <Link
                        to={appsPath}
                        onClick={() => setIsOpen(false)}
                        className="block w-full text-center text-sm text-blue-600 hover:text-blue-700 py-2 hover:bg-blue-50 rounded-lg transition-colors"
                    >
                        Manage Apps
                    </Link>
                </div>
            )}
        </div>
    );

    return (
        <>
            <button
                ref={buttonRef}
                onClick={() => {
                    setIsOpen(!isOpen);
                    // Initial calc on open
                    if (!isOpen) setTimeout(updatePosition, 0);
                }}
                className="flex items-center gap-2 px-3 py-2 rounded-lg hover:bg-slate-100 transition-colors"
                title="App Launcher"
            >
                <Grid3X3 size={20} className="text-slate-600" />
                {currentApp && (
                    <>
                        <span className="text-sm font-medium text-slate-700 hidden md:block">
                            {currentApp.label}
                        </span>
                        <ChevronDown size={16} className={`text-slate-500 transition-transform ${isOpen ? 'rotate-180' : ''}`} />
                    </>
                )}
            </button>

            {isOpen && createPortal(dropdownContent, document.body)}
        </>
    );
};
