import { usePage } from '@inertiajs/react'
import { ConfigDrawer } from '@ui/components/config-drawer'
import { AuthenticatedLayout } from '@ui/components/layout/authenticated-layout'
import { Header } from '@ui/components/layout/header'
import { ProfileDropdown } from '@ui/components/profile-dropdown'
import { Search } from '@ui/components/search'
import { ThemeSwitch } from '@ui/components/theme-switch'
import type { PropsWithChildren } from 'react'
import { useEffect, useState } from 'react'
import { financeSidebarData } from '@/layouts/sidebar-data'

type FinanceAppLayoutProps = PropsWithChildren

const authAppUrl = import.meta.env.VITE_AUTH_APP_URL || 'http://localhost:8000'
const navModeStorageKey = 'gfin-nav-mode'
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: '#', current: true, bg: 'bg-rose-600' },
  { id: 'portal', name: 'Portal', description: 'Customer Portal', url: import.meta.env.VITE_PORTAL_APP_URL || 'http://localhost:8001', current: false, bg: 'bg-cyan-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: import.meta.env.VITE_GLIMS_APP_URL || 'http://localhost:8005', current: false, 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 keuanganGroup = financeSidebarData.navGroups.find((group) => group.title === 'Keuangan')
const masterDataChildren = keuanganGroup?.items.find((item) => item.title === 'Data Master')?.items?.map((item) => ({ label: item.title, href: item.url })) ?? []
const transaksiChildren = keuanganGroup?.items.find((item) => item.title === 'Transaksi')?.items?.map((item) => ({ label: item.title, href: item.url })) ?? []
const reportChildren = keuanganGroup?.items.find((item) => item.title === 'Pelaporan')?.items?.map((item) => ({ label: item.title, href: item.url })) ?? []

const NAV_ITEMS = [
  { label: 'Dashboard', href: '/dashboard' },
  { label: 'Master Data', children: masterDataChildren },
  { label: 'Transaksi', children: transaksiChildren },
  { label: 'Report', children: reportChildren },
].filter((item) => ('href' in item) || ('children' in item && item.children.length > 0))

export function FinanceAppLayout({ children }: FinanceAppLayoutProps) {
  const { auth } = usePage().props
  const user = auth?.user
  const [navMode, setNavMode] = useState<'sidebar' | 'navbar'>('sidebar')
  const [openMenu, setOpenMenu] = useState<string | null>(null)
  const [switcherOpen, setSwitcherOpen] = useState(false)

  const handleSignOut = () => {
    window.location.href = authAppUrl + '/logout'
  }

  useEffect(() => {
    if (typeof window === 'undefined') return
    const saved = window.localStorage.getItem(navModeStorageKey)
    if (saved === 'navbar' || saved === 'sidebar') setNavMode(saved)
  }, [])

  const switchNavMode = (checked: boolean) => {
    const nextMode: 'sidebar' | 'navbar' = checked ? 'sidebar' : 'navbar'
    setNavMode(nextMode)
    if (typeof window !== 'undefined') {
      window.localStorage.setItem(navModeStorageKey, nextMode)
    }
    setOpenMenu(null)
  }

  const sidebarData = {
    ...financeSidebarData,
    user: {
      name: user?.name ?? 'User',
      email: user?.email ?? '',
      avatar: user?.avatar ?? '',
    },
  }

  if (navMode === 'navbar') {
    return (
      <div className='min-h-screen bg-gray-50 dark:bg-gray-900'>
        <nav className='sticky top-0 z-40 border-b border-rose-100 bg-white shadow-sm dark:border-rose-900/30 dark:bg-[#1A0F14]'>
          <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-rose-600 shadow-sm transition-colors group-hover:bg-rose-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='M3 10.5L12 3l9 7.5M5.25 9.75V21h13.5V9.75' />
                    </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 Finance'}</span>
                    <span className='block font-mono text-xs text-rose-500'>Finance Operations</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'>
                        {(() => {
                          const children = item.children ?? []
                          return (
                            <>
                        <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-rose-100 text-rose-700 dark:bg-rose-950/40 dark:text-rose-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] rounded-xl border border-gray-100 bg-white p-1.5 shadow-lg dark:border-gray-700 dark:bg-gray-800'>
                              {children.map((c) => (
                                <a key={c.href} href={c.href} onClick={() => setOpenMenu(null)} className={`block rounded-lg px-3 py-2 text-sm transition-colors ${isHrefActive(c.href) ? 'bg-rose-100 font-medium text-rose-700 dark:bg-rose-950/40 dark:text-rose-300' : 'text-gray-700 hover:bg-gray-50 dark:text-gray-300 dark:hover:bg-gray-700'}`}>
                                  {c.label}
                                </a>
                              ))}
                            </div>
                          </>
                        )}
                            </>
                          )
                        })()}
                      </div>
                    ) : (
                      <a key={item.href} href={item.href} className={`rounded-md px-3 py-2 text-sm font-medium transition-colors ${isHrefActive(item.href) ? 'bg-rose-100 text-rose-700 dark:bg-rose-950/40 dark:text-rose-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}
                      </a>
                    ),
                  )}
                </div>
              </div>

              <div className='flex items-center gap-2'>
                <div className='inline-flex items-center rounded-lg border border-gray-200 bg-gray-50 p-1 text-xs font-medium dark:border-gray-700 dark:bg-gray-800'>
                  <button
                    type='button'
                    className='rounded-md bg-rose-600 px-2.5 py-1 text-white shadow-sm'
                  >
                    Navbar
                  </button>
                  <button
                    type='button'
                    onClick={() => switchNavMode(true)}
                    className='rounded-md px-2.5 py-1 text-gray-600 transition-colors hover:bg-white hover:text-rose-600 dark:text-gray-300 dark:hover:bg-gray-700 dark:hover:text-rose-300'
                  >
                    Sidebar
                  </button>
                </div>
                <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-rose-300 hover:bg-white hover:text-rose-600 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-300 dark:hover:border-rose-700 dark:hover:text-rose-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>
    )
  }

  return (
    <AuthenticatedLayout onSignOut={handleSignOut} sidebarData={sidebarData} profileUrl='/settings/profile'>
      <Header fixed>
        <div className='ms-auto flex items-center space-x-4'>
          <div className='inline-flex items-center rounded-lg border border-gray-200 bg-gray-50 p-1 text-xs font-medium dark:border-gray-700 dark:bg-gray-800'>
            <button
              type='button'
              onClick={() => switchNavMode(false)}
              className='rounded-md px-2.5 py-1 text-gray-600 transition-colors hover:bg-white hover:text-rose-600 dark:text-gray-300 dark:hover:bg-gray-700 dark:hover:text-rose-300'
            >
              Navbar
            </button>
            <button
              type='button'
              className='rounded-md bg-rose-600 px-2.5 py-1 text-white shadow-sm'
            >
              Sidebar
            </button>
          </div>
          <Search />
          <ThemeSwitch />
          <ConfigDrawer />
          <ProfileDropdown
            user={user ? { name: user.name, email: user.email, avatar: user.avatar ?? '' } : undefined}
            onSignOut={handleSignOut}
            profileUrl='/settings/profile'
          />
        </div>
      </Header>
      {children}
    </AuthenticatedLayout>
  )
}

function isHrefActive(href: string): boolean {
  if (typeof window === 'undefined') return false
  const [hrefPath] = href.split('?')
  return window.location.pathname === hrefPath
}

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-rose-100 dark:bg-rose-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-rose-700 dark:text-rose-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-rose-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>
}
