'use client'

import { useEffect, useState } from 'react'
import Link from 'next/link'
import { ArrowUpRightIcon, MenuIcon, XIcon } from 'lucide-react'
import BlurEffect from 'react-progressive-blur'
import { AnimateIn, StandardSiteLogo } from '@/app/components'
import { EXTERNAL_LINKS, NAV_ITEMS, SECONDARY_NAV_ITEMS } from '@/app/data/content'
import { scrollToElement } from '@/app/lib/scroll'

export function MobileNav() {
    const [isOpen, setIsOpen] = useState(false)
    const [activeSection, setActiveSection] = useState<string>('#')

    useEffect(() => {
        if (isOpen) {
            document.body.style.overflow = 'hidden'
        } else {
            document.body.style.overflow = ''
        }

        return () => {
            document.body.style.overflow = ''
        }
    }, [isOpen])

    useEffect(() => {
        const sectionIds = NAV_ITEMS
            .map(item => item.href)
            .filter(href => href !== '#')
            .map(href => href.slice(1))

        const observers: IntersectionObserver[] = []

        sectionIds.forEach(id => {
            const element = document.getElementById(id)
            if (!element) return

            const observer = new IntersectionObserver(
                (entries) => {
                    entries.forEach(entry => {
                        if (entry.isIntersecting) {
                            setActiveSection(`#${id}`)
                        }
                    })
                },
                {
                    rootMargin: '-20% 0px -70% 0px',
                    threshold: 0
                }
            )

            observer.observe(element)
            observers.push(observer)
        })

        const handleScroll = () => {
            if (window.scrollY < 100) {
                setActiveSection('#')
            }
        }

        window.addEventListener('scroll', handleScroll)
        handleScroll()

        return () => {
            observers.forEach(observer => observer.disconnect())
            window.removeEventListener('scroll', handleScroll)
        }
    }, [])

    const handleNavClick = (href: string) => {
        setIsOpen(false)
        setTimeout(() => {
            scrollToElement(href)
        }, 100)
    }

    return (
        <>
            <AnimateIn
                as="header"
                direction="down"
                delay={ 0.5 }
                onScroll={ false }
                className="fixed left-0 right-0 top-0 z-30 px-4 py-2 md:hidden"
            >
                <div
                    className={ `p-4 relative flex flex-col gap-6 z-40 mx-auto max-w-[38rem] w-full min-h-0 overflow-hidden rounded-2xl transition-all duration-300 ease-in-out ${
                        isOpen
                            ? 'bg-zinc-950 dark:bg-zinc-50 text-zinc-50 dark:text-zinc-950 h-[31rem]'
                            : 'text-base-content h-15'
                    }` }>
                    <div className="flex justify-between items-center">
                        <StandardSiteLogo className="size-7" />
                        { !isOpen && (
                            <button
                                onClick={ () => setIsOpen(true) }
                                aria-label="Open menu"
                            >
                                <MenuIcon className="size-6" />
                            </button>
                        )}
                        { isOpen && (
                            <button
                                onClick={ () => setIsOpen(false) }
                                aria-label="Close menu"
                            >
                                <XIcon className="size-6" />
                            </button>
                        )}
                    </div>
                    <nav className="flex flex-col gap-4">
                        { NAV_ITEMS.map((item) => (
                            <a
                                key={ item.label }
                                href={ item.href }
                                onClick={ (e) => {
                                    e.preventDefault()
                                    handleNavClick(item.href)
                                } }
                                className={ `font-medium text-lg tracking-tight ${
                                    activeSection === item.href ? 'text-zinc-50 dark:text-zinc-950' : 'text-muted-content'
                                } hover:text-zinc-50 dark:hover:text-zinc-950 transition-colors` }
                            >
                                { item.label }
                            </a>
                        )) }

                        <div className="h-px w-full bg-border/10" />

                        { SECONDARY_NAV_ITEMS.map((item) => (
                            <Link
                                key={ item.label }
                                href={ item.href }
                                onClick={ () => setIsOpen(false) }
                                className="font-medium text-lg tracking-tight text-muted-content hover:text-zinc-50 dark:hover:text-zinc-950 transition-colors"
                            >
                                { item.label }
                            </Link>
                        )) }

                        <div className="h-px w-full bg-border/10" />

                        <nav className="flex flex-col gap-4">
                            { EXTERNAL_LINKS.map((link) => (
                                <a
                                    key={ link.label }
                                    href={ link.href }
                                    target="_blank"
                                    rel="noopener noreferrer"
                                    className="flex font-medium text-lg tracking-tight text-muted-content hover:text-zinc-50 dark:hover:text-zinc-950 transition-colors"
                                >
                                    { link.label }
                                    <ArrowUpRightIcon className="size-6 ml-auto"/>
                                </a>
                            )) }
                        </nav>
                    </nav>
                </div>
                <BlurEffect
                    className="bg-gradient-to-b from-base-100 to-transparent absolute inset-0 w-full h-full -z-10"
                    position="top"
                    intensity={ 75 }
                />
            </AnimateIn>

            {/* Overlay */}
            <div
                className={ `fixed inset-0 z-10 bg-base-100/50 backdrop-blur-sm transition-opacity duration-300 md:hidden ${
                    isOpen ? 'opacity-100' : 'opacity-0 pointer-events-none'
                }` }
                onClick={ () => setIsOpen(false) }
            />
        </>
    )
}
