'use client'
import { useHeaderTheme } from '@/providers/HeaderTheme'
import Link from 'next/link'
import { usePathname } from 'next/navigation'
import React, { useEffect, useState } from 'react'

import type { Header, Page } from '@/payload-types'
import type { SocialLinkData } from '@/components/SocialIcons'

import { Logo } from '@/components/Logo/Logo'
import { HeaderNav } from './Nav'

interface HeaderClientProps {
  data: Header
  socialLinks?: SocialLinkData[]
}

function resolveLogoHref(logoLink: Header['logoLink']): string {
  if (!logoLink) return '/'
  if (logoLink.type === 'reference') {
    const ref = logoLink.reference
    if (ref && typeof ref === 'object' && 'value' in ref) {
      const page = ref.value
      return typeof page === 'object' && page !== null ? `/${(page as Page).slug}` : '/'
    }
    return '/'
  }
  return logoLink.url || '/'
}

export const HeaderClient: React.FC<HeaderClientProps> = ({ data, socialLinks = [] }) => {
  const [theme, setTheme] = useState<string | null>(null)
  const [isDark, setIsDark] = useState(false)
  const { headerTheme, setHeaderTheme } = useHeaderTheme()
  const pathname = usePathname()

  useEffect(() => {
    const mq = window.matchMedia('(prefers-color-scheme: dark)')
    setIsDark(mq.matches)
    const handler = (e: MediaQueryListEvent) => setIsDark(e.matches)
    mq.addEventListener('change', handler)
    return () => mq.removeEventListener('change', handler)
  }, [])

  useEffect(() => {
    setHeaderTheme(null)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pathname])

  useEffect(() => {
    if (headerTheme && headerTheme !== theme) setTheme(headerTheme)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [headerTheme])

  const logoHref = resolveLogoHref(data?.logoLink)

  return (
    <header
      className="relative z-20 w-full bg-white dark:bg-fd-navy border-b border-transparent dark:border-white/10"
      {...(theme ? { 'data-theme': theme } : {})}
    >
      <div className="container py-5 flex justify-between items-center">
        <Link href={logoHref}>
          <Logo loading="eager" priority="high" variant={isDark ? 'white' : 'blue'} className="max-w-[80px] md:max-w-[100px]" />
        </Link>
        <HeaderNav data={data} socialLinks={socialLinks} />
      </div>
    </header>
  )
}
