"use client";

import React, { useState, useRef, useCallback } from 'react';
import Link from 'next/link';
import Image from 'next/image';
import { Button } from '../elements';
import { getLogoUrl } from '../../utils/photo-helpers';
import type { HeaderComponentProps } from './header-navigation';
import type { NavItem } from '../../types/config';
import { resolveCtaUrls, isExternalCtaUrl } from '../../lib/cta-urls';

// Maximum items to show before "View All" link
const MAX_DROPDOWN_ITEMS = 6;

export function HeaderNavigation({ 
    props, 
    navigation: navigationOverride, 
    logoImage: logoImageOverride, 
    logoText: logoTextOverride, 
    config,
    companyInformation,
    websitePhotos,
}: HeaderComponentProps) {
    const [activeDropdown, setActiveDropdown] = useState<string | null>(null);
    const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
    
    // Timeout ref for delayed dropdown closing
    const closeTimeoutRef = useRef<NodeJS.Timeout | null>(null);
    
    // Cleanup timeout on unmount
    React.useEffect(() => {
        return () => {
            if (closeTimeoutRef.current) {
                clearTimeout(closeTimeoutRef.current);
            }
        };
    }, []);
    
    const logoUrl = logoImageOverride || getLogoUrl(websitePhotos) || props?.logo?.image;
    const companyName = logoTextOverride || companyInformation?.company_name || props?.logo?.text || '';
    
    // Use navigation from config or override
    const navigation = navigationOverride || config?.navigation?.header || [];
    const ctaUrls = resolveCtaUrls(companyInformation, props?.cta_button, {
        primaryHrefOverride: props?.primaryHrefOverride,
        secondaryHrefOverride: props?.secondaryHrefOverride,
    });

    // Cancel any pending close timeout
    const cancelCloseTimeout = useCallback(() => {
        if (closeTimeoutRef.current) {
            clearTimeout(closeTimeoutRef.current);
            closeTimeoutRef.current = null;
        }
    }, []);

    // Open dropdown immediately
    const handleMouseEnter = useCallback((item: NavItem) => {
        cancelCloseTimeout();
        if (item.children && item.children.length > 0) {
            setActiveDropdown(item.label);
        }
    }, [cancelCloseTimeout]);

    // Close dropdown with delay (allows moving to dropdown)
    const handleMouseLeave = useCallback(() => {
        cancelCloseTimeout();
        closeTimeoutRef.current = setTimeout(() => {
            setActiveDropdown(null);
        }, 150); // 150ms delay before closing
    }, [cancelCloseTimeout]);

    // Keep dropdown open when hovering over it
    const handleDropdownMouseEnter = useCallback(() => {
        cancelCloseTimeout();
    }, [cancelCloseTimeout]);

    // Close dropdown when leaving the dropdown area
    const handleDropdownMouseLeave = useCallback(() => {
        handleMouseLeave();
    }, [handleMouseLeave]);

    // Get display items for dropdown (limit + "View All" if needed)
    const getDropdownItems = (item: NavItem) => {
        const children = item.children || [];
        
        if (children.length > MAX_DROPDOWN_ITEMS + 1) {
            // Show first MAX_DROPDOWN_ITEMS items + "View All" link
            const displayItems = children.slice(0, MAX_DROPDOWN_ITEMS);
            return {
                items: displayItems,
                showViewAll: true,
                viewAllHref: item.href,
                viewAllLabel: `View All`,
            };
        }
        
        return {
            items: children,
            showViewAll: false,
            viewAllHref: '',
            viewAllLabel: '',
        };
    };

    return (
        <>
            {/* Desktop Header */}
            <header className="hidden md:block sticky top-0 z-50 bg-primary border-b border-primary">
                <div className="mx-auto max-w-7xl px-4 md:px-8">
                    <div className="flex items-center justify-between py-4">
                        {/* Left: Logo */}
                        <Link href="/" className="flex items-center flex-shrink-0">
                            {logoUrl ? (
                                <Image 
                                    src={logoUrl} 
                                    alt={companyName}
                                    className="h-10 w-auto object-contain"
                                    width={120}
                                    height={40}
                                />
                            ) : (
                                <span className="font-display text-xl font-normal text-fg-primary">
                                    {companyName}
                                </span>
                            )}
                        </Link>

                        {/* Navigation */}
                        <nav className="flex items-center gap-8 flex-1 ml-12">
                            {navigation.map((item: NavItem, i: number) => (
                                <div
                                    key={i}
                                    className="relative"
                                    onMouseEnter={() => handleMouseEnter(item)}
                                    onMouseLeave={handleMouseLeave}
                                >
                                    <Link
                                        href={item.href}
                                        className="font-body text-md font-normal text-fg-primary hover:text-brand-accent transition-colors duration-200 flex items-center gap-1 whitespace-nowrap"
                                    >
                                        {item.label}
                                        {item.children && item.children.length > 0 && (
                                            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                                            </svg>
                                        )}
                                    </Link>
                                    
                                    {/* Dropdown Menu - Simple vertical list */}
                                    {item.children && item.children.length > 0 && activeDropdown === item.label && (
                                        <div 
                                            className="absolute left-0 top-full mt-2 w-64 py-3 bg-white border border-secondary rounded-lg shadow-lg z-50"
                                            onMouseEnter={handleDropdownMouseEnter}
                                            onMouseLeave={handleDropdownMouseLeave}
                                        >
                                            {(() => {
                                                const { items, showViewAll, viewAllHref, viewAllLabel } = getDropdownItems(item);
                                                return (
                                                    <>
                                                        {items.map((link: NavItem, j: number) => (
                                                            <Link
                                                                key={j}
                                                                href={link.href}
                                                                className="block font-body text-md text-fg-primary hover:text-brand-accent hover:bg-secondary transition-colors px-4 py-2"
                                                            >
                                                                {link.label}
                                                            </Link>
                                                        ))}
                                                        {showViewAll && (
                                                            <Link
                                                                href={viewAllHref}
                                                                className="block font-body text-md text-brand-accent hover:underline px-4 py-2 font-semibold border-t border-secondary mt-2 pt-3"
                                                            >
                                                                {viewAllLabel} →
                                                            </Link>
                                                        )}
                                                    </>
                                                );
                                            })()}
                                        </div>
                                    )}
                                </div>
                            ))}
                        </nav>

                        {/* Right: CTA Buttons - Left=Contact Us (/contact), Right=Book Now (booking) */}
                        <div className="flex items-center gap-3 flex-shrink-0 ml-4">
                            {props?.cta_button?.secondary_label && ctaUrls.hasSecondary && (
                                <Button
                                    href={ctaUrls.secondaryHref}
                                    target={props.cta_button.secondary_target}
                                    rel={props.cta_button.secondary_target === '_blank' ? 'noopener noreferrer' : undefined}
                                    color="secondary"
                                    size="sm"
                                >
                                    {props.cta_button.label}
                                </Button>
                            )}
                            <Button
                                href={ctaUrls.primaryHref}
                                target={props?.cta_button?.target ?? (isExternalCtaUrl(ctaUrls.primaryHref) ? '_blank' : undefined)}
                                rel={(props?.cta_button?.target === '_blank' || isExternalCtaUrl(ctaUrls.primaryHref)) ? 'noopener noreferrer' : undefined}
                                color="primary"
                                size="sm"
                            >
                                {(props?.cta_button?.secondary_label && ctaUrls.hasSecondary) ? props.cta_button.secondary_label : (props?.cta_button?.label || "")}
                            </Button>
                        </div>
                    </div>
                </div>
            </header>

            {/* Mobile Header */}
            <header className="md:hidden sticky top-0 z-50 bg-primary border-b border-secondary">
                <div className="flex items-center justify-between px-4 py-4">
                    <button
                        onClick={() => setIsMobileMenuOpen(true)}
                        className="text-fg-primary"
                        aria-label="Open menu"
                    >
                        <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16M4 18h16" />
                        </svg>
                    </button>
                    
                    <Link href="/" className="flex items-center">
                        {logoUrl ? (
                            <Image 
                                src={logoUrl} 
                                alt={companyName}
                                className="h-8 w-auto object-contain"
                                width={120}
                                height={32}
                            />
                        ) : (
                            <span className="font-display text-lg font-normal text-fg-primary">
                                {companyName}
                            </span>
                        )}
                    </Link>
                    
                    <div className="w-6" />
                </div>
            </header>

            {/* Mobile Full-Screen Menu Overlay */}
            {isMobileMenuOpen && (
                <div className="fixed inset-0 bg-white z-50 md:hidden">
                    <div className="flex flex-col h-full">
                        {/* Mobile Menu Header */}
                        <div className="flex items-center justify-between px-4 py-4 border-b border-secondary">
                            <button
                                onClick={() => setIsMobileMenuOpen(false)}
                                className="text-fg-primary"
                                aria-label="Close menu"
                            >
                                <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                                </svg>
                            </button>
                            
                            <div className="flex items-center">
                                {logoUrl ? (
                                    <Image 
                                        src={logoUrl} 
                                        alt={companyName}
                                        className="h-8 w-auto object-contain"
                                        width={120}
                                        height={32}
                                    />
                                ) : (
                                    <span className="font-display text-lg font-normal text-fg-primary">
                                        {companyName}
                                    </span>
                                )}
                            </div>
                            
                            <div className="w-6" />
                        </div>

                        {/* Mobile Menu Links */}
                        <nav className="flex-1 overflow-y-auto px-4 py-8">
                            <ul className="space-y-4">
                                {navigation.map((item: NavItem, i: number) => {
                                    const { items } = getDropdownItems(item);
                                    return (
                                        <li key={i}>
                                            <Link
                                                href={item.href}
                                                className="block font-body text-base text-fg-primary py-2 font-medium"
                                                onClick={() => setIsMobileMenuOpen(false)}
                                            >
                                                {item.label}
                                            </Link>
                                            {items.length > 0 && (
                                                <ul className="ml-4 mt-2 space-y-2">
                                                    {items.map((link: NavItem, j: number) => (
                                                        <li key={j}>
                                                            <Link
                                                                href={link.href}
                                                                className="block font-body text-sm text-tertiary py-1"
                                                                onClick={() => setIsMobileMenuOpen(false)}
                                                            >
                                                                {link.label}
                                                            </Link>
                                                        </li>
                                                    ))}
                                                </ul>
                                            )}
                                        </li>
                                    );
                                })}
                            </ul>
                        </nav>

                        {/* Mobile Menu Footer */}
                        <div className="border-t border-secondary px-4 py-6">
                            <div className="flex flex-col gap-3">
                                {props?.cta_button?.secondary_label && ctaUrls.hasSecondary && (
                                    <Button
                                        href={ctaUrls.secondaryHref}
                                        color="secondary"
                                        size="sm"
                                        className="w-full"
                                        onClick={() => setIsMobileMenuOpen(false)}
                                    >
                                        {props.cta_button.secondary_label}
                                    </Button>
                                )}
                                <Button
                                    href={ctaUrls.primaryHref}
                                    color="primary"
                                    size="sm"
                                    className="w-full"
                                    onClick={() => setIsMobileMenuOpen(false)}
                                >
                                    {props?.cta_button?.label || ""}
                                </Button>
                            </div>
                        </div>
                    </div>
                </div>
            )}

            {/* Sticky Book/Contact bar (mobile only) - matches barelux theme */}
            <div className="fixed bottom-0 left-0 right-0 z-40 md:hidden bg-fg-primary">
                <div className="flex gap-0">
                    {props?.cta_button?.secondary_label && ctaUrls.hasSecondary && (
                            <Button
                                href={ctaUrls.secondaryHref}
                                target={props.cta_button.secondary_target}
                                rel={props.cta_button.secondary_target === '_blank' ? 'noopener noreferrer' : undefined}
                                color="primary"
                                className="flex-1 font-body text-sm uppercase tracking-wide py-4 rounded-none border-r border-white/20"
                            >
                                {props.cta_button.label}
                            </Button>
                        )}
                        <Button
                            href={ctaUrls.primaryHref}
                            target={props?.cta_button?.target ?? (isExternalCtaUrl(ctaUrls.primaryHref) ? '_blank' : undefined)}
                            rel={(props?.cta_button?.target === '_blank' || isExternalCtaUrl(ctaUrls.primaryHref)) ? 'noopener noreferrer' : undefined}
                            color="primary"
                            className={`${props?.cta_button?.secondary_label && ctaUrls.hasSecondary ? 'flex-1' : 'w-full'} font-body text-sm uppercase tracking-wide py-4 rounded-none`}
                        >
                            {(props?.cta_button?.secondary_label && ctaUrls.hasSecondary) ? props.cta_button.secondary_label : (props?.cta_button?.label || "Contact")}
                        </Button>
                </div>
            </div>
        </>
    );
}

import { registerThemeVariant } from '../../lib/component-registry';
registerThemeVariant('header-navigation', 'barelux', HeaderNavigation);
