'use client'

import type { MobileNavigation } from '@/payload-types'

import { cn } from '@/utilities/cn'
import { MenuIcon, MessageCircle } from 'lucide-react'
import Link from 'next/link'
import { usePathname } from 'next/navigation'
import React from 'react'

import { MobileNavigationDrawer } from './Drawer'
import { mobileNavigationIcons } from './icons'

type MobileNavItem = NonNullable<MobileNavigation['navItems']>[number]

type Props = {
  mobileNavigation: MobileNavigation
  variant?: 'bottom' | 'trigger'
}

const fallbackNavItems: MobileNavItem[] = [
  {
    icon: 'home',
    id: 'fallback-home',
    link: {
      label: 'Home',
      type: 'custom',
      url: '/',
    },
  },
  {
    icon: 'shop',
    id: 'fallback-shop',
    link: {
      label: 'Shop',
      type: 'custom',
      url: '/shop',
    },
  },
  {
    icon: 'artikel',
    id: 'fallback-artikel',
    link: {
      label: 'Artikel',
      type: 'custom',
      url: '/artikel',
    },
  },
  {
    icon: 'contact',
    id: 'fallback-contact',
    link: {
      label: 'Kontak',
      type: 'custom',
      url: '/contact',
    },
  },
  {
    icon: 'menu',
    id: 'fallback-menu',
    link: {
      label: 'Menu',
      type: 'custom',
      url: '#',
    },
  },
]

const getLinkHref = (item: MobileNavItem['link']) => {
  if (
    item.type === 'reference' &&
    typeof item.reference?.value === 'object' &&
    item.reference.value.slug
  ) {
    return `/${item.reference.value.slug}`
  }

  return item.url || '/'
}

const normalizeWhatsAppPhone = (value?: null | string) => value?.replace(/[^\d]/g, '') || ''

export function MobileNavigationClient({ mobileNavigation, variant = 'bottom' }: Props) {
  const pathname = usePathname()

  if (mobileNavigation.enabled === false) {
    return null
  }

  const navItems = mobileNavigation.navItems?.length ? mobileNavigation.navItems : fallbackNavItems
  const drawerItems = mobileNavigation.drawerItems?.length
    ? mobileNavigation.drawerItems
    : mobileNavigation.navItems || []
  const whatsApp = mobileNavigation.floatingWhatsApp
  const whatsAppPhone = normalizeWhatsAppPhone(whatsApp?.phoneNumber)
  const whatsAppHref = whatsAppPhone
    ? `https://wa.me/${whatsAppPhone}?text=${encodeURIComponent(whatsApp?.message || '')}`
    : null

  if (variant === 'trigger') {
    return (
      <MobileNavigationDrawer
        items={drawerItems.length ? drawerItems : navItems}
        trigger={
          <button
            aria-label="Open mobile menu"
            className="inline-flex h-10 w-10 items-center justify-center rounded-full text-primary transition-colors hover:bg-muted hover:text-primary md:hidden"
            type="button"
          >
            <MenuIcon className="h-5 w-5" strokeWidth={2} />
          </button>
        }
      />
    )
  }

  return (
    <>
      {whatsApp?.enabled && whatsAppHref ? (
        <div className="pointer-events-none fixed inset-x-0 bottom-[calc(var(--bmj-mobile-nav-offset,0px)+0.85rem)] z-40 flex justify-end px-4 md:hidden">
          <Link
            aria-label={whatsApp.label || 'Chat WhatsApp'}
            className="pointer-events-auto relative grid h-12 w-12 place-items-center rounded-full bg-[#25d366] text-white shadow-lg shadow-[#063f2b]/25 ring-4 ring-background transition hover:scale-105"
            href={whatsAppHref}
            rel="noopener noreferrer"
            target="_blank"
          >
            <MessageCircle className="h-5 w-5" />
            <span className="pointer-events-none absolute inset-0 -z-10 animate-ping rounded-full bg-[#25d366]/35" />
          </Link>
        </div>
      ) : null}

      <nav
        aria-label="Mobile navigation"
        className="fixed inset-x-0 bottom-0 z-40 border-t border-[#dbe8d7] bg-[#fffaf2]/95 pb-[env(safe-area-inset-bottom)] shadow-[0_-18px_50px_rgba(6,63,43,0.12)] backdrop-blur md:hidden"
      >
        <div className="mx-auto flex max-w-md items-stretch px-2">
          {navItems.map((item) => {
            const href = getLinkHref(item.link)
            const Icon = mobileNavigationIcons[item.icon || 'home'] || mobileNavigationIcons.home
            const isActive =
              href === '/' ? pathname === '/' : pathname === href || pathname.startsWith(`${href}/`)

            if (item.icon === 'menu') {
              return (
                <MobileNavigationDrawer
                  items={drawerItems.length ? drawerItems : navItems}
                  key={item.id}
                  trigger={
                    <button
                      aria-label={item.link.label || 'Menu'}
                      className="flex flex-1 flex-col items-center justify-center gap-1 rounded-2xl px-2 py-2 text-[0.68rem] font-semibold text-[#607668] transition hover:bg-white/70 hover:text-[#14422d]"
                      type="button"
                    >
                      <Icon className="h-5 w-5" strokeWidth={2} />
                      <span>{item.link.label || 'Menu'}</span>
                    </button>
                  }
                />
              )
            }

            return (
              <Link
                aria-current={isActive ? 'page' : undefined}
                className={cn(
                  'flex flex-1 flex-col items-center justify-center gap-1 rounded-2xl px-2 py-2 text-[0.68rem] font-semibold text-[#607668] transition',
                  isActive
                    ? 'bg-white text-[#063f2b] shadow-sm shadow-[#063f2b]/10'
                    : 'hover:bg-white/70 hover:text-[#14422d]',
                )}
                href={href}
                key={item.id}
              >
                <Icon className="h-5 w-5" strokeWidth={2} />
                <span>{item.link.label}</span>
              </Link>
            )
          })}
        </div>
      </nav>
    </>
  )
}
