import { isSafeNavigationUrl } from '../../core/navigation/navigationUrl';
import React from 'react';
import { NavLink } from 'react-router-dom';
import {
    Settings, FileCode, ExternalLink, ChevronLeft, ChevronRight
} from 'lucide-react';
import { useApp } from '@nexuscrm/host-sdk';
import { useSystemPermission } from '@nexuscrm/host-sdk';
import { hostApps, type HostSidebarSystemItemContribution } from '@nexuscrm/host-sdk';
import { Tooltip } from '../ui/Tooltip';
import { ROUTES } from '../../core/constants/Routes';
import { tryBuildAppNavigationPath } from '../../core/navigation/appNavigationCapabilities';
import { tryGetSetupBasePath, tryGetSetupCapabilityPagePath } from '../../core/navigation/setupPagePaths';
import { resolveObjectNavIconName } from '../../core/navigation/objectNavIcons';
import { lucideIconComponent, type LucideIconComponent } from '../../core/icons/lucideIconComponents';

interface SidebarProps {
    isSidebarCollapsed: boolean;
    setIsSidebarCollapsed: (collapsed: boolean) => void;
    mobileMenuOpen: boolean;
    setMobileMenuOpen: (open: boolean) => void;
}

interface SidebarSystemItemLinkProps {
    item: HostSidebarSystemItemContribution;
    currentFrontendAppId: string | null | undefined;
    isSidebarCollapsed: boolean;
    showLabels: boolean;
}

interface CrmSidebarNavigationItem {
    id: string;
    type: string;
    label: string;
    icon?: string;
    objectApiName?: string;
    pageUrl?: string;
    dashboardId?: string;
}

interface CrmSidebarAppConfig {
    id?: string;
    frontendAppId?: string | null;
    navigationItems?: CrmSidebarNavigationItem[] | null;
}

function sidebarSystemItemPath(
    item: HostSidebarSystemItemContribution,
    currentFrontendAppId: string | null | undefined,
): string | undefined {
    if (item.route.kind === 'appNavigation') {
        return tryBuildAppNavigationPath(
            currentFrontendAppId,
            item.route.capability as Parameters<typeof tryBuildAppNavigationPath>[1],
            item.route.params,
        );
    }
    return tryGetSetupCapabilityPagePath(
        currentFrontendAppId,
        item.route.capability as Parameters<typeof tryGetSetupCapabilityPagePath>[1],
    );
}

const SidebarSystemItemLink: React.FC<SidebarSystemItemLinkProps> = ({
    item,
    currentFrontendAppId,
    isSidebarCollapsed,
    showLabels,
}) => {
    const hasRequiredCapability = useSystemPermission(item.requiredCapability ?? '');
    const path = sidebarSystemItemPath(item, currentFrontendAppId);
    if (!path || (item.requiredCapability && !hasRequiredCapability)) {
        return null;
    }

    const Icon = item.icon;
    const Badge = item.badge;
    const link = (
        <NavLink
            to={path}
            className={({ isActive }) => `flex items-center gap-3 px-3 py-2 rounded-xl text-sm font-medium transition-all duration-200 ${isActive ? 'text-white shadow-md' : 'text-slate-600 hover:bg-white/60 hover:text-slate-900'} ${isSidebarCollapsed ? 'justify-center' : ''}`}
            style={({ isActive }) => isActive ? { backgroundColor: 'var(--color-brand)' } : {}}
        >
            <div className="relative">
                <Icon size={20} className="shrink-0" />
                {Badge && <Badge showLabels={false} />}
            </div>
            {showLabels && (
                <span className="flex items-center gap-2">
                    {item.label}
                    {Badge && <Badge showLabels />}
                </span>
            )}
        </NavLink>
    );

    return (!showLabels) ? (
        <Tooltip content={item.label} position="right">{link}</Tooltip>
    ) : link;
};

export const Sidebar: React.FC<SidebarProps> = ({
    isSidebarCollapsed,
    setIsSidebarCollapsed,
    mobileMenuOpen,
    setMobileMenuOpen,
}) => {
    const { currentApp, currentAppId, currentFrontendAppId, visibleApps = [], appLoadError, refreshApps } = useApp();
    const sidebarSystemItems = hostApps.apps.get(currentFrontendAppId)
        ?.shellComponents?.sidebarSystemItems ?? [];
    const hasViewSetup = useSystemPermission('ViewSetup');

    // Resolve a nav item's icon to a lucide component. Prefers the item's own
    // icon name; when that is empty or not a valid lucide export, object tabs
    // fall back to an API-name-derived icon (self-healing when the persisted
    // iconUrl was dropped by a Tooling `tabs` edit), everything else to FileCode.
    const getNavItemIcon = (item: CrmSidebarNavigationItem): LucideIconComponent => {
        const fallbackName = item.type === 'object'
            ? resolveObjectNavIconName(item.objectApiName)
            : 'FileCode';
        return lucideIconComponent(item.icon?.trim())
            ?? lucideIconComponent(fallbackName)
            ?? (FileCode as unknown as LucideIconComponent);
    };

    const selectedApp = currentApp as CrmSidebarAppConfig | null;
    const appWithNavigationItems = selectedApp && (!currentAppId || selectedApp.id === currentAppId)
        ? selectedApp
        : (visibleApps as CrmSidebarAppConfig[]).find(app => app.id === currentAppId) ?? null;
    const itemsToRender = appLoadError ? [] : appWithNavigationItems?.navigationItems || [];
    const hasNavigationItems = itemsToRender.length > 0;
    const showLabels = !isSidebarCollapsed || mobileMenuOpen;
    const setupPath = tryGetSetupBasePath(currentFrontendAppId);

    return (
        <>
            {/* Mobile Backdrop */}
            {mobileMenuOpen && (
                <div
                    className="fixed inset-0 z-[90] bg-black/50 lg:hidden backdrop-blur-sm transition-opacity"
                    onClick={() => setMobileMenuOpen(false)}
                />
            )}

            <aside
                className={`
            fixed inset-y-0 left-0 z-[100] h-full lg:static lg:h-auto
            ${isSidebarCollapsed ? 'lg:w-20' : 'lg:w-64'}
            w-64 bg-white/50 backdrop-blur-lg border-r border-slate-200/60 
            flex flex-col transition-all duration-300 ease-in-out
            ${mobileMenuOpen ? 'translate-x-0 shadow-2xl' : '-translate-x-full lg:translate-x-0'}
          `}
            >
                {/* Scrollable Navigation Items */}
                <nav className="flex-1 overflow-y-auto p-3 space-y-1">
                    {appLoadError && <div role="alert" className="p-2 text-sm text-amber-700">
                        Navigation is unavailable.
                        <button className="block underline" onClick={() => { void refreshApps(); }}>Retry navigation</button>
                    </div>}
                    {/* Navigation Items from App */}
                    {hasNavigationItems && (
                        <>
                            {itemsToRender.map(item => {
                                if ((item.type === 'web' || item.type === 'page') && item.pageUrl && !isSafeNavigationUrl(item.pageUrl)) return null;
                                const IconComponent = getNavItemIcon(item);

                                const content = (
                                    <>
                                        <IconComponent size={20} className="shrink-0" />
                                        {showLabels && (
                                            <span className="truncate">{item.label}</span>
                                        )}
                                        {showLabels && item.type === 'web' && (
                                            <ExternalLink size={12} className="ml-auto text-slate-400 shrink-0" />
                                        )}
                                    </>
                                );

                                const commonClasses = ({ isActive }: { isActive: boolean }) =>
                                    `flex items-center gap-3 px-3 py-2.5 rounded-xl text-sm font-medium transition-all duration-200 ${isActive
                                        ? 'bg-slate-100 text-slate-900'
                                        : 'text-slate-600 hover:bg-white/60 hover:text-slate-900'
                                    } ${isSidebarCollapsed ? 'justify-center' : ''}`;


                                // Web tabs
                                if (item.type === 'web' && item.pageUrl) {
                                    const link = (
                                        <a
                                            key={item.id}
                                            href={item.pageUrl}
                                            target="_blank"
                                            rel="noopener noreferrer"
                                            className={commonClasses({ isActive: false })}
                                        >
                                            {content}
                                        </a>
                                    );
                                    return isSidebarCollapsed ? (
                                        <Tooltip key={item.id} content={item.label} position="right">
                                            {link}
                                        </Tooltip>
                                    ) : link;
                                }

                                // Object tabs use NavLink
                                const getNavRoute = () => {
                                    if (item.type === 'dashboard' && item.dashboardId) {
                                        return tryBuildAppNavigationPath(currentFrontendAppId, 'dashboardDetail', { dashboardId: item.dashboardId });
                                    }
                                    if (item.type === 'page' && item.pageUrl) {
                                        return item.pageUrl;
                                    }
                                    if (item.type === 'object' && item.objectApiName) {
                                        return ROUTES.OBJECT.LIST(item.objectApiName);
                                    }
                                    return undefined;
                                };
                                const route = getNavRoute();
                                if (!route) return null;

                                const navLink = (
                                    <NavLink
                                        key={item.id}
                                        to={route}
                                        end={item.pageUrl === '/'}
                                        className={commonClasses}
                                    >
                                        {content}
                                    </NavLink>
                                );

                                return isSidebarCollapsed ? (
                                    <Tooltip key={item.id} content={item.label} position="right">
                                        {navLink}
                                    </Tooltip>
                                ) : navLink;
                            })}
                        </>
                    )}
                </nav>

                {/* Fixed System Footer */}
                <div className="p-3 border-t border-slate-200/60 bg-white/30 backdrop-blur-sm">
                    {!isSidebarCollapsed && (
                        <div className="px-3 text-xs font-semibold text-slate-400 uppercase tracking-wider mb-2 animate-in fade-in duration-200">System</div>
                    )}

                    {hasViewSetup && setupPath && (() => {
                        const setupLink = (
                            <NavLink
                                to={setupPath}
                                end
                                className={({ isActive }) => `flex items-center gap-3 px-3 py-2 rounded-xl text-sm font-medium transition-all duration-200 ${isActive ? 'text-white shadow-md' : 'text-slate-600 hover:bg-white/60 hover:text-slate-900'} ${isSidebarCollapsed ? 'justify-center' : ''}`}
                                style={({ isActive }) => isActive ? { backgroundColor: 'var(--color-brand)' } : {}}
                            >
                                <Settings size={20} className="shrink-0" />
                                {showLabels && <span>Setup</span>}
                            </NavLink>
                        );
                        return (!showLabels) ? (
                            <Tooltip content="Setup" position="right">{setupLink}</Tooltip>
                        ) : setupLink;
                    })()}

                    {sidebarSystemItems.map(item => (
                        <SidebarSystemItemLink
                            key={item.id}
                            item={item}
                            currentFrontendAppId={currentFrontendAppId}
                            isSidebarCollapsed={isSidebarCollapsed}
                            showLabels={showLabels}
                        />
                    ))}

                    {/* Collapse Toggle - Desktop Only */}
                    <button
                        onClick={() => setIsSidebarCollapsed(!isSidebarCollapsed)}
                        className={`hidden lg:flex mt-2 w-full items-center gap-3 px-3 py-2 rounded-xl text-sm font-medium text-slate-400 hover:bg-white/60 hover:text-slate-700 transition-all ${isSidebarCollapsed ? 'justify-center' : ''}`}
                        title={isSidebarCollapsed ? "Expand Sidebar" : "Collapse Sidebar"}
                    >
                        {isSidebarCollapsed ? <ChevronRight size={20} /> : <ChevronLeft size={20} />}
                        {!isSidebarCollapsed && <span>Collapse</span>}
                    </button>
                </div>
            </aside>
        </>
    );
};
