'use client'

import { CMSLink } from '@/components/Link'
import { Cart } from '@/components/Cart'
import { CurrencySelector } from '@/components/CurrencySelector'
import { MobileNavigationClient } from '@/components/MobileNavigation/index.client'
import { OpenCartButton } from '@/components/Cart/OpenCart'
import { useAuth } from '@/providers/Auth'
import { cn } from '@/utilities/cn'
import { Leaf, Search, User } from 'lucide-react'
import Link from 'next/link'
import { usePathname } from 'next/navigation'
import React, { Suspense } from 'react'

import type { Header, MobileNavigation } from 'src/payload-types'

type Props = {
  header: Header
  mobileNavigation: MobileNavigation
}

const actionButtonClassName =
  'inline-flex h-10 w-10 items-center justify-center rounded-full text-primary transition-colors hover:bg-muted hover:text-primary dark:text-foreground dark:hover:bg-muted'

function getLinkHref(item: NonNullable<Header['navItems']>[number]['link']) {
  if (
    item.type === 'reference' &&
    typeof item.reference?.value === 'object' &&
    item.reference.value.slug
  ) {
    return `/${item.reference.value.slug}`
  }

  return item.url || ''
}

function isAccountLink(href: string) {
  return href === '/account' || href === '/login' || href === '/create-account'
}

export function HeaderClient({ header, mobileNavigation }: Props) {
  const { user } = useAuth()
  const menu = header.navItems || []
  const pathname = usePathname()
  const accountHref = user ? '/account' : '/login'
  const desktopMenu = menu.filter((item) => {
    const href = getLinkHref(item.link)

    return !isAccountLink(href)
  })

  return (
    <div className="sticky top-0 z-30 border-b border-border bg-background/90 backdrop-blur">
      <nav className="flex justify-between items-center w-full px-4 md:px-16 py-4 max-w-7xl mx-auto gap-4">
        <Link className="flex items-center gap-3 text-primary" href="/">
          <span className="inline-flex h-9 w-9 items-center justify-center rounded-full border border-border bg-card">
            <Leaf className="h-4 w-4 text-primary" strokeWidth={2.25} />
          </span>
          <span className="font-serif text-2xl font-semibold leading-none tracking-tight">
            Bunga Mekarsari
          </span>
        </Link>

        {desktopMenu.length ? (
          <ul className="hidden flex-1 items-center justify-center gap-8 md:flex">
            {desktopMenu.map((item) => {
              const href = getLinkHref(item.link)

              return (
                <li key={item.id}>
                  <CMSLink
                    {...item.link}
                    className={cn(
                      'navLink relative pb-1 text-sm font-bold text-muted-foreground transition-colors hover:text-primary',
                      {
                        active: href
                          ? pathname === href || (href !== '/' && pathname.startsWith(href))
                          : false,
                      },
                    )}
                  />
                </li>
              )
            })}
          </ul>
        ) : (
          <div className="hidden flex-1 md:block" />
        )}

        <div className="ml-auto flex items-center gap-1">
          <Link aria-label="Search products" className={actionButtonClassName} href="/shop">
            <Search className="h-5 w-5" strokeWidth={2} />
          </Link>

          <Suspense fallback={null}>
            <CurrencySelector />
          </Suspense>

          <Suspense fallback={<OpenCartButton />}>
            <Cart />
          </Suspense>

          <Link
            aria-label="Account"
            className={cn(actionButtonClassName, 'hidden md:inline-flex')}
            href={accountHref}
          >
            <User className="h-5 w-5" strokeWidth={2} />
          </Link>

          <Suspense fallback={null}>
            <MobileNavigationClient mobileNavigation={mobileNavigation} variant="trigger" />
          </Suspense>
        </div>
      </nav>
    </div>
  )
}
