import { usePage } from '@inertiajs/react'
import { ProfileDropdown } from '@ui/components/profile-dropdown'
import { ThemeSwitch } from '@ui/components/theme-switch'
import type { PropsWithChildren } from 'react'
import { useState } from 'react'
import { limsSidebarData } from './sidebar-data'

type LimsAppLayoutProps = PropsWithChildren

const SWITCH_APPS = [
    { id: 'auth',   name: 'GMP Auth',    description: 'Identity & SSO',            url: import.meta.env.VITE_AUTH_APP_URL   || 'http://localhost:8000', current: false, bg: 'bg-indigo-600' },
    { id: 'gfin',   name: 'GMP Finance', description: 'Keuangan & Akuntansi',      url: import.meta.env.VITE_GFIN_APP_URL   || 'http://localhost:8002', current: false, bg: 'bg-emerald-600' },
    { id: 'portal', name: 'Portal',      description: 'Customer Portal',            url: import.meta.env.VITE_PORTAL_APP_URL || 'http://localhost:8001', current: false, bg: 'bg-blue-500',   disabled: true },
    { id: 'gris',   name: 'GRIS',        description: 'Governance & Risk',          url: import.meta.env.VITE_GRIS_APP_URL   || 'http://localhost:8003', current: false, bg: 'bg-orange-500', disabled: true },
    { id: 'glims',  name: 'GLIMS',       description: 'Lab Information Management', url: '#',                                                            current: true,  bg: 'bg-teal-600' },
    { id: 'gwin',   name: 'GWIN',        description: 'Warehouse & Inventory',      url: import.meta.env.VITE_GWIN_APP_URL   || 'http://localhost:8006', current: false, bg: 'bg-amber-600' },
] as const

const NAV_ITEMS = limsSidebarData.navGroups
    .map((group) => {
        const children = group.items
            .map((item) => {
                if (item.url) {
                    return { label: item.title, href: item.url }
                }

                if (item.items && item.items.length > 0) {
                    // Keep grouped modules accessible via parent menu only.
                    return { label: item.title, href: item.items[0].url }
                }

                return null
            })
            .filter((item): item is { label: string; href: string } => item !== null)

        if (children.length === 1 && group.title === 'Umum') {
            return { label: children[0].label, href: children[0].href }
        }

        return { label: group.title, children }
    })
    .filter((item) => ('href' in item) || ('children' in item && item.children.length > 0))

const authAppUrl = import.meta.env.VITE_AUTH_APP_URL || 'http://localhost:8000'

export function LimsAppLayout({ children }: LimsAppLayoutProps) {
    const { auth } = usePage().props
    const user = auth?.user
    const handleSignOut = () => {
        window.location.href = authAppUrl + '/logout'
    }

    const [switcherOpen, setSwitcherOpen] = useState(false)
    const [openMenu, setOpenMenu] = useState<string | null>(null)

    return (
        <div className='min-h-screen bg-gray-50 dark:bg-gray-900'>
            <nav className='sticky top-0 z-40 border-b border-teal-100 bg-white shadow-sm dark:border-teal-900/30 dark:bg-gray-900'>
                <div className='mx-auto max-w-screen-2xl px-4 sm:px-6 lg:px-8'>
                    <div className='flex h-16 items-center justify-between'>

                        <div className='flex items-center gap-4'>
                            <a href='/dashboard' className='group flex items-center gap-2.5'>
                                <div className='flex h-8 w-8 items-center justify-center rounded-lg bg-teal-600 shadow-sm transition-colors group-hover:bg-teal-700'>
                                    <svg className='text-white' style={{ width: 18, height: 18 }} fill='none' viewBox='0 0 24 24' stroke='currentColor' strokeWidth={2}>
                                        <path strokeLinecap='round' strokeLinejoin='round' d='M9.75 3.104v5.714a2.25 2.25 0 01-.659 1.591L5 14.5M9.75 3.104c-.251.023-.501.05-.75.082m.75-.082a24.301 24.301 0 014.5 0m0 0v5.714c0 .597.237 1.17.659 1.591L19.8 15.3M14.25 3.104c.251.023.501.05.75.082M19.8 15.3l-1.57.393A9.065 9.065 0 0112 15a9.065 9.065 0 00-6.23-.693L5 14.5m14.8.8l1.402 1.402c1.232 1.232.65 3.318-1.067 3.611A48.309 48.309 0 0112 21a48.25 48.25 0 01-8.135-.687c-1.718-.293-2.3-2.379-1.067-3.61L5 14.5' />
                                    </svg>
                                </div>
                                <div className='leading-none'>
                                    <span className='block text-sm font-semibold text-gray-900 dark:text-gray-100'>{import.meta.env.VITE_APP_NAME || 'GMP LIMS'}</span>
                                    <span className='block font-mono text-xs text-teal-500'>Lab Information</span>
                                </div>
                            </a>

                            <div className='hidden items-center gap-0.5 lg:flex'>
                                {NAV_ITEMS.map((item) =>
                                    'children' in item ? (
                                        <div key={item.label} className='relative'>
                                            <button
                                                onClick={() => setOpenMenu((p) => p === item.label ? null : item.label)}
                                                className={`flex items-center gap-1 rounded-md px-3 py-2 text-sm font-medium transition-colors ${openMenu === item.label ? 'bg-teal-50 text-teal-700 dark:bg-teal-950/40 dark:text-teal-300' : 'text-gray-600 hover:bg-gray-50 hover:text-gray-900 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-100'}`}
                                            >
                                                {item.label}
                                                <svg className={`h-3.5 w-3.5 transition-transform ${openMenu === item.label ? 'rotate-180' : ''}`} fill='none' viewBox='0 0 24 24' stroke='currentColor' strokeWidth={2.5}>
                                                    <path strokeLinecap='round' strokeLinejoin='round' d='M19.5 8.25l-7.5 7.5-7.5-7.5' />
                                                </svg>
                                            </button>
                                            {openMenu === item.label && (
                                                <>
                                                    <div className='fixed inset-0 z-10' onClick={() => setOpenMenu(null)} />
                                                    <div className='absolute left-0 top-full z-20 mt-1 min-w-[210px] max-h-[calc(100vh-5.5rem)] overflow-y-auto overscroll-contain rounded-xl border border-gray-100 bg-white p-1.5 shadow-lg dark:border-gray-700 dark:bg-gray-800'>
                                                        {item.children.map((c) => <DropdownLink key={c.href} href={c.href} label={c.label} onNavigate={() => setOpenMenu(null)} />)}
                                                    </div>
                                                </>
                                            )}
                                        </div>
                                    ) : (
                                        <NavLink key={item.href} href={item.href} label={item.label} />
                                    ),
                                )}
                            </div>
                        </div>

                        <div className='flex items-center gap-2'>
                            <ThemeSwitch />

                            <div className='relative'>
                                <button
                                    onClick={() => setSwitcherOpen((o) => !o)}
                                    className='flex items-center gap-1.5 rounded-lg border border-gray-200 bg-gray-50 px-3 py-1.5 text-xs font-medium text-gray-600 transition-colors hover:border-teal-300 hover:bg-white hover:text-teal-600 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-300 dark:hover:border-teal-700 dark:hover:text-teal-400'
                                >
                                    <svg className='h-3.5 w-3.5' fill='none' viewBox='0 0 24 24' stroke='currentColor' strokeWidth={2}>
                                        <path strokeLinecap='round' strokeLinejoin='round' d='M3.75 6A2.25 2.25 0 016 3.75h2.25A2.25 2.25 0 0110.5 6v2.25a2.25 2.25 0 01-2.25 2.25H6a2.25 2.25 0 01-2.25-2.25V6zM3.75 15.75A2.25 2.25 0 016 13.5h2.25a2.25 2.25 0 012.25 2.25V18a2.25 2.25 0 01-2.25 2.25H6A2.25 2.25 0 013.75 18v-2.25zM13.5 6a2.25 2.25 0 012.25-2.25H18A2.25 2.25 0 0120.25 6v2.25A2.25 2.25 0 0118 10.5h-2.25a2.25 2.25 0 01-2.25-2.25V6zM13.5 15.75a2.25 2.25 0 012.25-2.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-2.25A2.25 2.25 0 0113.5 18v-2.25z' />
                                    </svg>
                                    Aplikasi
                                    <svg className={`h-3 w-3 transition-transform ${switcherOpen ? 'rotate-180' : ''}`} fill='none' viewBox='0 0 24 24' stroke='currentColor' strokeWidth={2.5}>
                                        <path strokeLinecap='round' strokeLinejoin='round' d='M19.5 8.25l-7.5 7.5-7.5-7.5' />
                                    </svg>
                                </button>
                                {switcherOpen && (
                                    <>
                                        <div className='fixed inset-0 z-10' onClick={() => setSwitcherOpen(false)} />
                                        <div className='absolute right-0 top-full z-20 mt-2 w-64 max-h-[calc(100vh-5.5rem)] overflow-y-auto overscroll-contain rounded-xl border border-gray-200 bg-white p-2 shadow-lg dark:border-gray-700 dark:bg-gray-800'>
                                            <p className='px-2 pb-1.5 pt-1 text-xs font-semibold uppercase tracking-wider text-gray-400 dark:text-gray-500'>GMP Platform</p>
                                            {SWITCH_APPS.map((app) => <SwitcherItem key={app.id} app={app} />)}
                                        </div>
                                    </>
                                )}
                            </div>

                            <ProfileDropdown
                                user={user ? { name: user.name, email: user.email, avatar: user.avatar ?? '' } : undefined}
                                onSignOut={handleSignOut}
                                profileUrl='/settings/profile'
                            />
                        </div>

                    </div>
                </div>
            </nav>

            <main>{children}</main>
        </div>
    )
}

function NavLink({ href, label }: { href: string; label: string }) {
    const active = isHrefActive(href)
    return (
        <a href={href} className={`rounded-md px-3 py-2 text-sm font-medium transition-colors ${active ? 'bg-teal-50 text-teal-700 dark:bg-teal-950/40 dark:text-teal-300' : 'text-gray-600 hover:bg-gray-50 hover:text-gray-900 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-100'}`}>
            {label}
        </a>
    )
}

function DropdownLink({ href, label, onNavigate }: { href: string; label: string; onNavigate: () => void }) {
    const active = isHrefActive(href)
    return (
        <a href={href} onClick={onNavigate} className={`block rounded-lg px-3 py-2 text-sm transition-colors ${active ? 'bg-teal-50 font-medium text-teal-700 dark:bg-teal-950/40 dark:text-teal-300' : 'text-gray-700 hover:bg-gray-50 dark:text-gray-300 dark:hover:bg-gray-700'}`}>
            {label}
        </a>
    )
}

function isHrefActive(href: string): boolean {
    if (typeof window === 'undefined') {
        return false
    }

    const [hrefPath, hrefQuery] = href.split('?')
    const pathnameMatches = window.location.pathname === hrefPath

    if (!pathnameMatches) {
        return false
    }

    if (!hrefQuery) {
        return true
    }

    const expectedParams = new URLSearchParams(hrefQuery)
    const currentParams = new URLSearchParams(window.location.search)

    for (const [key, value] of expectedParams.entries()) {
        if (currentParams.get(key) !== value) {
            return false
        }
    }

    return true
}

function SwitcherItem({ app }: { app: (typeof SWITCH_APPS)[number] }) {
    const isDisabled = 'disabled' in app && app.disabled
    const inner = (
        <div className={`flex items-center gap-3 rounded-lg px-2 py-2 transition-colors ${app.current ? 'bg-teal-50 dark:bg-teal-900/30' : isDisabled ? 'cursor-not-allowed opacity-50' : 'cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700'}`}>
            <div className={`flex h-7 w-7 flex-shrink-0 items-center justify-center rounded-md ${app.bg}`}><span className='h-2 w-2 rounded-full bg-white/80' /></div>
            <div className='min-w-0 flex-1'>
                <p className={`text-sm font-medium ${app.current ? 'text-teal-700 dark:text-teal-300' : 'text-gray-700 dark:text-gray-200'}`}>{app.name}</p>
                <p className='truncate text-xs text-gray-400 dark:text-gray-500'>{app.description}</p>
            </div>
            {app.current && <span className='flex-shrink-0 text-xs font-medium text-teal-500'>OK</span>}
            {isDisabled && <span className='flex-shrink-0 rounded-full bg-gray-100 px-1.5 py-0.5 text-xs text-gray-400 dark:bg-gray-700'>Soon</span>}
        </div>
    )
    if (app.current || isDisabled) return inner
    return <a href={app.url} className='block'>{inner}</a>
}
