'use client'

import Link from 'next/link'
import { usePathname, useRouter, useSearchParams } from 'next/navigation'
import {
  Bell,
  CalendarCheck,
  ChevronLeft,
  ChevronRight,
  ClipboardList,
  Download,
  FileText,
  Cpu,
  GraduationCap,
  LogOut,
  PackageCheck,
  PanelsTopLeft,
  Settings,
  User,
  UserCheck,
} from 'lucide-react'
import type { LucideIcon } from 'lucide-react'
import { useEffect, useState } from 'react'
import type { CartItemType } from '@/components/providers/AppProvider'
import { useApp } from '@/components/providers/AppProvider'

const orderSubItems: { label: string; type: CartItemType }[] = [
  { label: '课程', type: 'course' },
  { label: '活动', type: 'event' },
  { label: '数据', type: 'data' },
  { label: '智能体', type: 'agent' },
  { label: '专家预约', type: 'expert' },
  { label: '规划咨询', type: 'consulting' },
  { label: '会员', type: 'membership' },
]

type AccountNavChild = { label: string; type: CartItemType }
type AccountNavItem = { label: string; href: string; icon: LucideIcon; children?: AccountNavChild[] }
type AccountNavGroup = { label: string; items: AccountNavItem[] }

const profileItem: AccountNavItem = { label: '我的', href: '/account/membership', icon: User }

const navGroups: AccountNavGroup[] = [
  {
    label: '服务',
    items: [
      { label: '我的订单', href: '/account/orders', icon: PackageCheck, children: orderSubItems },
      { label: '我的发票', href: '/account/invoices', icon: FileText },
      { label: '我的咨询', href: '/account/consulting', icon: ClipboardList },
      { label: '专家预约', href: '/account/expert-bookings', icon: UserCheck },
      { label: '我的课程', href: '/account/courses', icon: GraduationCap },
      { label: '报名活动', href: '/account/events', icon: CalendarCheck },
      { label: '数据服务', href: '/account/data', icon: Download },
      { label: '我的智能体', href: '/account/agents', icon: Cpu },
      { label: '消息通知', href: '/account/notifications', icon: Bell },
    ],
  },
  {
    label: '账户',
    items: [
      { label: '账户设置', href: '/account/settings', icon: Settings },
    ],
  },
]

function isActive(pathname: string, href: string) {
  if (href === '/account') return pathname === href
  return pathname === href || pathname.startsWith(`${href}/`)
}

export function AccountShell({ children }: { children: React.ReactNode }) {
  const pathname = usePathname()
  const searchParams = useSearchParams()
  const router = useRouter()
  const { user, logout, accountSyncing, hydrated } = useApp()
  const [collapsed, setCollapsed] = useState(false)
  const [loggingOut, setLoggingOut] = useState(false)
  const activeOrderType = searchParams.get('type')
  const queryString = searchParams.toString()
  const needsOnboarding = Boolean(user && !user.onboardingCompleted)
  const expertHomeItem: AccountNavItem = { label: '专家主页', href: '/account/expert-home', icon: PanelsTopLeft }
  const showExpertHome = Boolean(
    user?.expertProfileStatus
    || user?.expertApplicationStatus === 'pending'
    || user?.expertApplicationStatus === 'approved'
    || user?.expertApplicationStatus === 'submitted'
    || user?.expertApplicationStatus === 'profile-review'
    || user?.expertApplicationStatus === 'profile-approved',
  )
  const visibleNavGroups: AccountNavGroup[] = navGroups.map((group) => (
    group.label === '账户' && showExpertHome
      ? { ...group, items: [expertHomeItem, ...group.items] }
      : group
  ))

  useEffect(() => {
    if (!hydrated || accountSyncing) return
    if (!needsOnboarding) return
    const redirect = `${pathname || '/account'}${queryString ? `?${queryString}` : ''}`
    router.replace(`/onboarding?redirect=${encodeURIComponent(redirect)}`)
  }, [accountSyncing, hydrated, needsOnboarding, pathname, queryString, router])

  if (loggingOut) return null
  if (!hydrated || accountSyncing) {
    return (
      <section className="grid min-h-[calc(100vh-70px)] place-items-center bg-bg px-6">
        <div className="text-sm font-extrabold text-muted">正在同步账号资料...</div>
      </section>
    )
  }
  if (needsOnboarding) {
    return (
      <section className="grid min-h-[calc(100vh-70px)] place-items-center bg-bg px-6">
        <div className="text-sm font-extrabold text-muted">跳转中...</div>
      </section>
    )
  }
  if (!user) return <>{children}</>

  return (
    <section className="bg-bg">
      <div className={`mx-auto min-h-[calc(100vh-70px)] max-w-[1440px] px-4 py-6 transition-[padding] duration-300 ease-out md:px-6 ${collapsed ? 'lg:pl-[96px]' : 'lg:pl-[244px]'}`}>
        <aside className={`fixed left-[max(1.5rem,calc((100vw-1440px)/2+1.5rem))] top-[calc(50vh+35px)] z-40 hidden h-[min(700px,calc(100vh-118px))] -translate-y-1/2 flex-col overflow-hidden rounded-[4px] border border-line bg-white shadow-[0_14px_42px_rgba(15,23,42,0.07)] transition-[width] duration-300 ease-out lg:flex ${collapsed ? 'w-[56px]' : 'w-[204px]'}`}>
          <div className={`flex h-14 items-center ${collapsed ? 'px-0' : 'px-2.5'} ${collapsed ? 'justify-center' : 'justify-between'}`}>
            <div className={`overflow-hidden whitespace-nowrap px-2 text-base font-extrabold text-ink transition-opacity duration-150 ${collapsed ? 'w-0 opacity-0' : 'opacity-100 delay-150'}`}>
              个人中心
            </div>
            <button
              type="button"
              onClick={() => setCollapsed((value) => !value)}
              className={`${collapsed ? 'h-9 w-full' : 'h-8 w-8'} grid shrink-0 place-items-center rounded-[4px] text-muted transition-colors duration-200 hover:bg-bg hover:text-brand`}
              aria-label={collapsed ? '展开侧边栏' : '收起侧边栏'}
            >
              {collapsed ? <ChevronRight className="h-4 w-4 -translate-x-px" /> : <ChevronLeft className="h-4 w-4" />}
            </button>
          </div>

          <nav className="min-h-0 flex-1 overflow-y-auto px-2.5 pb-2">
            <div className="mb-4">
              <Link
                href={profileItem.href}
                title={collapsed ? profileItem.label : undefined}
                className={`-mx-2.5 flex h-9 items-center gap-2.5 border-y text-sm font-bold transition-[background-color,border-color,color] duration-200 ease-out ${
                  isActive(pathname, profileItem.href)
                    ? 'border-brand/25 bg-brand/10 text-brand'
                    : 'border-transparent text-text-body hover:border-brand/15 hover:bg-brand/10 hover:text-brand'
                } ${collapsed ? 'justify-center px-0' : 'px-5'}`}
              >
                {collapsed ? <User className="h-4 w-4" /> : <span className="overflow-hidden whitespace-nowrap transition-opacity duration-150 opacity-100 delay-150">{profileItem.label}</span>}
              </Link>
            </div>
            {visibleNavGroups.map((group) => (
              <div key={group.label} className="mb-4 last:mb-0">
                <div className={`mb-2 overflow-hidden whitespace-nowrap px-2.5 text-[11px] font-extrabold tracking-[0.08em] text-soft transition-opacity duration-150 ${collapsed ? 'h-0 opacity-0' : 'opacity-100 delay-150'}`}>{group.label}</div>
                <div className="grid gap-1">
                  {group.items.map((item) => {
                    const active = isActive(pathname, item.href)
                    const Icon = item.icon
                    return (
                      <div key={item.href}>
                        <Link
                          href={item.href}
                          title={collapsed ? item.label : undefined}
                          className={`-mx-2.5 flex h-9 items-center gap-2.5 border-y text-sm font-bold transition-[background-color,border-color,color] duration-200 ease-out ${
                            active
                              ? 'border-brand/25 bg-brand/10 text-brand'
                              : 'border-transparent text-text-body hover:border-brand/15 hover:bg-brand/10 hover:text-brand'
                          } ${collapsed ? 'justify-center px-0' : 'px-5'}`}
                        >
                          {collapsed ? <Icon className="h-4 w-4" /> : <span className="overflow-hidden whitespace-nowrap transition-opacity duration-150 opacity-100 delay-150">{item.label}</span>}
                        </Link>
                        {'children' in item && item.children && (
                          <div className={`ml-6 mt-1 grid gap-1 border-l border-line pl-2 transition-opacity duration-150 ${collapsed ? 'hidden opacity-0' : 'opacity-100 delay-150'}`}>
                            {item.children.map((child) => {
                              const childActive = activeOrderType === child.type

                              return (
                                <Link
                                  key={child.type}
                                  href={`/account/orders?type=${child.type}`}
                                  className={`overflow-hidden whitespace-nowrap px-2.5 py-1.5 text-xs font-bold transition-[background-color,border-color,color,opacity] duration-200 ease-out ${
                                    childActive ? 'border-y border-brand/20 bg-brand/10 text-brand' : 'border-y border-transparent text-muted hover:border-brand/15 hover:bg-brand/10 hover:text-brand'
                                  }`}
                                >
                                  {child.label}
                                </Link>
                              )
                            })}
                          </div>
                        )}
                      </div>
                    )
                  })}
                </div>
              </div>
            ))}
          </nav>

          <div className="px-2.5 py-2">
            <button
              type="button"
              onClick={() => {
                setLoggingOut(true)
                logout()
                if (typeof window !== 'undefined') {
                  window.location.replace('/')
                  return
                }
                router.replace('/')
              }}
              className={`flex h-9 w-full items-center gap-2.5 rounded-[4px] px-2.5 text-sm font-bold text-muted transition-colors duration-200 hover:bg-bg hover:text-brand ${collapsed ? 'justify-center' : ''}`}
              title={collapsed ? '退出登录' : undefined}
            >
              {collapsed ? <LogOut className="h-4 w-4" /> : <span className="overflow-hidden whitespace-nowrap transition-opacity duration-150 opacity-100 delay-150">退出登录</span>}
            </button>
          </div>
        </aside>

        <div className="min-w-0">
          <div className="sticky top-[70px] z-30 mb-4 rounded-[4px] border border-line bg-white px-3 py-2 lg:hidden">
            <div className="mb-2 px-1 text-sm font-extrabold text-ink">个人中心</div>
            <div className="flex gap-2 overflow-x-auto">
              {[profileItem, ...visibleNavGroups.flatMap((group) => group.items)].map((item) => {
                const active = isActive(pathname, item.href)
                return (
                  <Link
                    key={item.href}
                    href={item.href}
                    className={`shrink-0 rounded-[4px] px-3 py-2 text-xs font-bold ${active ? 'bg-brand/10 text-brand' : 'bg-bg text-text-body'}`}
                  >
                    {item.label}
                  </Link>
                )
              })}
            </div>
            {pathname.startsWith('/account/orders') && (
              <div className="mt-2 flex gap-2 overflow-x-auto border-t border-line pt-2">
                {orderSubItems.map((item) => (
                  <Link
                    key={item.type}
                    href={`/account/orders?type=${item.type}`}
                    className={`shrink-0 rounded-[4px] px-3 py-1.5 text-xs font-bold ${
                      activeOrderType === item.type ? 'bg-brand/10 text-brand' : 'bg-bg text-muted'
                    }`}
                  >
                    {item.label}
                  </Link>
                ))}
              </div>
            )}
          </div>
          {children}
        </div>
      </div>
    </section>
  )
}
