'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 } from '@/payload-types'

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

type CategoryItem = {
  id: string | number
  title: string
  slug: string
  parent?: any | null
}

export type NavCategoriesData = {
  parents: CategoryItem[]
  children: CategoryItem[]
}

interface HeaderClientProps {
  data: Header | null
  categories?: NavCategoriesData
}

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

  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])

  return (
    <header className="container relative z-20" {...(theme ? { 'data-theme': theme } : {})}>
      <div className="py-8 flex justify-between">
        <Link href="/">
          <Logo
            loading="eager"
            priority="high"
            className=""
            logo={typeof data?.logo === 'object' ? (data.logo as any) : null}
          />
        </Link>
        <HeaderNav data={data} categories={categories} />
      </div>
    </header>
  )
}
