'use client';

import { Fragment, useState, useEffect } from 'react';
import { Menu, MenuButton, MenuItem, MenuItems, Transition } from '@headlessui/react';
import { ArrowDown01Icon, ArrowRight01Icon, Menu01Icon, User03Icon, DashboardSquare03Icon, Logout02Icon } from '@zen/core/shared/icons';
import { UserAvatar } from '@zen/core/shared/components';
import { useRouter, usePathname } from 'next/navigation';
import { getPage } from '../registry.js';
import { useTheme, getThemeIcon } from '@zen/core/themes';
import Link from 'next/link';

const AdminTop = ({ isMobileMenuOpen, setIsMobileMenuOpen, user, onLogout, appName = 'ZEN', navigationSections = [] }) => {
    const router = useRouter();
    const pathname = usePathname();
    const [pageTitle, setPageTitle] = useState('');

    useEffect(() => {
        const segments = pathname.replace(/^\/admin\/?/, '').split('/').filter(Boolean);
        const slug = segments[0] || 'dashboard';
        setPageTitle(getPage(slug)?.title || '');
    }, [pathname]);

    const handleLogout = async () => {
        try {
            if (onLogout) {
                const result = await onLogout();
                if (result && result.success) {
                    router.push('/auth/login');
                } else {
                    console.error('Logout failed:', result?.error);
                    router.push('/auth/login');
                }
            } else {
                router.push('/auth/login');
            }
        } catch (error) {
            console.error('Logout error:', error);
            router.push('/auth/login');
        }
    };

    const { theme, toggle, systemIsDark } = useTheme();
    const ThemeIcon = getThemeIcon(theme, systemIsDark);
    const themeLabel = theme === 'light' ? 'Mode clair' : theme === 'dark' ? 'Mode sombre' : 'Thème système';

    const buildBreadcrumbs = () => {
        const crumbs = [{ icon: DashboardSquare03Icon, href: '/admin/dashboard' }];
        const after = pathname.replace(/^\/admin\/?/, '');
        const segments = after.split('/').filter(Boolean);

        if (!after || !segments.length || (segments[0] === 'dashboard' && segments.length === 1)) {
            crumbs.push({ label: pageTitle });
            return crumbs;
        }

        // Localise l'item actif via match le plus long (href exact > basePath préfixe).
        // On recalcule côté client pour rester aligné sur AdminSidebar et suivre les
        // navigations Link sans dépendre d'un re-render serveur du layout.
        const matchLen = (item) => {
            if (pathname === item.href) return item.href.length;
            const basePath = item.basePath || item.href;
            if (pathname === basePath) return basePath.length;
            if (pathname.startsWith(basePath + '/')) return basePath.length;
            return 0;
        };

        let activeSection = null;
        let activeItem = null;
        let activeLen = 0;
        for (const section of navigationSections) {
            for (const item of section.items) {
                const len = matchLen(item);
                if (len > activeLen) {
                    activeSection = section;
                    activeItem = item;
                    activeLen = len;
                }
            }
        }

        if (!activeItem) {
            // Page enregistrée hors navigation (ex : /admin/profile).
            crumbs.push({ label: pageTitle });
            return crumbs;
        }

        // Préfixer la section uniquement si elle ne se résume pas à un item unique
        // du même nom (cas « direct link » dans la sidebar — section.title === item.name,
        // ex : section "Utilisateurs" + item "Utilisateurs").
        if (activeSection.title !== activeItem.name) {
            crumbs.push({ label: activeSection.title });
        }

        const isExactPage = pathname === activeItem.href;
        crumbs.push({ label: activeItem.name, href: isExactPage ? undefined : activeItem.href });

        // Action de sous-route : segment juste après le basePath (/edit/:id, /new).
        const basePath = activeItem.basePath || activeItem.href;
        const trail = pathname.startsWith(basePath)
            ? pathname.slice(basePath.length).split('/').filter(Boolean)
            : [];
        const action = trail[0];
        if (action === 'new') {
            const page = getPage(`${segments[0]}:new`);
            crumbs.push({ label: page?.breadcrumbLabel || page?.title || 'Nouveau' });
        } else if (action === 'edit') {
            const page = getPage(`${segments[0]}:edit`);
            crumbs.push({ label: page?.breadcrumbLabel || page?.title || 'Modification' });
        }

        return crumbs;
    };

    const breadcrumbs = buildBreadcrumbs();

    return (
        <header className="bg-white dark:bg-black border-b border-neutral-200 dark:border-neutral-800/70 sticky top-0 z-30 h-12 flex items-center w-full">
            <div className="flex items-center justify-between px-4 lg:px-6 py-2 w-full">
                {/* Left section — Mobile menu button + Logo / Desktop breadcrumb */}
                <div className="flex items-center space-x-3 lg:hidden">
                    <button
                        onClick={() => setIsMobileMenuOpen(!isMobileMenuOpen)}
                        className="p-1 rounded-md text-neutral-500 dark:text-neutral-400 hover:text-neutral-900 dark:hover:text-white transition-colors duration-150"
                        aria-label="Toggle menu"
                    >
                        <Menu01Icon className="h-5 w-5 transition-transform duration-200" />
                    </button>
                    <h1 className="text-neutral-900 dark:text-white font-semibold text-sm">{appName}</h1>
                </div>

                {/* Desktop breadcrumb — always rendered to keep user menu pinned right */}
                <div className="hidden lg:flex items-center gap-1.5 text-[13px]">
                    {breadcrumbs.length > 0 && breadcrumbs.map((crumb, i) => (
                        <Fragment key={i}>
                            {i > 0 && (
                                <ArrowRight01Icon className="w-3 h-3 text-neutral-400 dark:text-neutral-600 flex-shrink-0" />
                            )}
                            {crumb.icon ? (
                                <button
                                    onClick={() => router.push(crumb.href)}
                                    className="text-neutral-500 dark:text-neutral-400 hover:text-neutral-900 dark:hover:text-white transition-colors cursor-pointer"
                                >
                                    <crumb.icon className="w-4 h-4" />
                                </button>
                            ) : crumb.href ? (
                                <button
                                    onClick={() => router.push(crumb.href)}
                                    className="text-neutral-500 dark:text-neutral-400 hover:text-neutral-900 dark:hover:text-white transition-colors cursor-pointer"
                                >
                                    {crumb.label}
                                </button>
                            ) : (
                                <span className="text-neutral-900 dark:text-white font-medium">{crumb.label}</span>
                            )}
                        </Fragment>
                    ))}
                </div>

                {/* Right section — Profile */}
                <div className="flex items-center gap-3 sm:gap-4">
                    {/* User Profile Menu */}
                    <Menu as="div" className="relative">
                        <MenuButton className="cursor-pointer flex items-center gap-2.5 px-2.5 py-1.5 rounded-xl hover:bg-black/5 dark:hover:bg-white/5 transition-colors duration-200 outline-none group">
                            <UserAvatar user={user} size="sm" />
                            {/* Name — desktop only */}
                            <span className="hidden sm:block text-[13px] leading-none font-medium text-neutral-800 dark:text-white">
                                {user?.name || 'User'}
                            </span>
                            <ArrowDown01Icon className="w-3.5 h-3.5 shrink-0 text-neutral-400 dark:text-neutral-600 transition-transform duration-200 group-data-open:rotate-180" />
                        </MenuButton>

                        <Transition
                            as={Fragment}
                            enter="transition ease-out duration-150"
                            enterFrom="opacity-0 translate-y-1"
                            enterTo="opacity-100 translate-y-0"
                            leave="transition ease-in duration-100"
                            leaveFrom="opacity-100 translate-y-0"
                            leaveTo="opacity-0 translate-y-1"
                        >
                            <MenuItems className="absolute right-0 mt-4 w-48 outline-none rounded-xl border border-black/8 dark:border-white/8 bg-white dark:bg-[#0B0B0B] shadow-lg overflow-hidden z-50">
                                <div className="p-1.5 flex flex-col gap-0.5">
                                    {/* Profile */}
                                    <MenuItem>
                                        <Link
                                            href="/admin/profile"
                                            className="cursor-pointer w-full flex items-center gap-2 px-[7px] py-[10px] rounded-lg text-[13px] leading-none text-neutral-500 dark:text-neutral-400 transition-colors duration-[120ms] ease-out data-focus:bg-neutral-100 dark:data-focus:bg-white/5 data-focus:text-neutral-900 dark:data-focus:text-white"
                                        >
                                            <User03Icon className="w-4 h-4 shrink-0" />
                                            Mon profil
                                        </Link>
                                    </MenuItem>

                                    {/* Theme — pas de MenuItem pour ne pas fermer le menu au clic */}
                                    <button
                                        onClick={toggle}
                                        className="cursor-pointer w-full flex items-center gap-2 px-[7px] py-[10px] rounded-lg text-[13px] leading-none text-neutral-500 dark:text-neutral-400 hover:bg-amber-50 dark:hover:bg-amber-500/10 hover:text-amber-500 dark:hover:text-amber-400 transition-colors duration-150"
                                    >
                                        <ThemeIcon className="w-4 h-4 shrink-0" />
                                        {themeLabel}
                                    </button>

                                    <div className="h-px bg-black/6 dark:bg-white/6 my-0.5" />

                                    {/* Logout */}
                                    <MenuItem>
                                        <button
                                            onClick={handleLogout}
                                            className="cursor-pointer w-full flex items-center gap-2 px-[7px] py-[10px] rounded-lg text-[13px] leading-none text-red-700 dark:text-red-600 transition-colors duration-150 text-left data-focus:bg-red-700/10 dark:data-focus:bg-red-700/20"
                                        >
                                            <Logout02Icon className="w-4 h-4 shrink-0" />
                                            Se déconnecter
                                        </button>
                                    </MenuItem>
                                </div>
                            </MenuItems>
                        </Transition>
                    </Menu>
                </div>
            </div>
        </header>
    );
};

export default AdminTop;
