"use client";

import React, { useState, useRef, useCallback } from 'react';
import Link from 'next/link';
import Image from 'next/image';
import { Button } from '../elements';
import { cx } from '../../utils/cx';
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 = 3;

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);
  const [dropdownTop, setDropdownTop] = useState(0);
  const [isScrolled, setIsScrolled] = useState(false);
  
  // Timeout ref for delayed dropdown closing
  const closeTimeoutRef = useRef<NodeJS.Timeout | null>(null);
  
  // Track scroll position for header animation
  React.useEffect(() => {
    const handleScroll = () => {
      setIsScrolled(window.scrollY > 10);
    };
    
    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  }, []);
  
  // 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, e: React.MouseEvent<HTMLDivElement>) => {
    cancelCloseTimeout();
    if (item.children && item.children.length > 0) {
      const target = e.currentTarget.closest('nav');
      if (target) {
        const rect = target.getBoundingClientRect();
        setDropdownTop(rect.bottom);
      }
      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 || [];
    const isDynamicMenu = item.label === 'Services' || item.label === 'Locations';
    
    if (isDynamicMenu && children.length > MAX_DROPDOWN_ITEMS + 1) {
      // Show first MAX_DROPDOWN_ITEMS items + "View All" link
      const displayItems = children.slice(0, MAX_DROPDOWN_ITEMS);
      const viewAllHref = item.label === 'Services' ? '/services' : '/locations';
      return {
        items: displayItems,
        showViewAll: true,
        viewAllHref,
        viewAllLabel: `View All ${item.label}`,
      };
    }
    
    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-secondary transition-all duration-300">
        <div className="mx-auto max-w-container px-4 md:px-8">
          {/* Top Row: Logo (left), Company Name (center), Contact Button (right) */}
          <div className={cx(
            "relative flex items-center justify-between transition-all duration-300",
            isScrolled ? "py-2" : "py-8"
          )}>
            {/* Left: Logo Image */}
            <Link href="/" className="flex items-center">
              {logoUrl && (
                <Image 
                  src={logoUrl} 
                  alt={companyName}
                  className="h-8 md:h-10 w-auto object-contain"
                  width={120}
                  height={40}
                />
              )}
            </Link>

            {/* Center: Company Name Text */}
            <Link href="/" className="absolute left-1/2 transform -translate-x-1/2 font-display text-2xl md:text-3xl font-normal uppercase tracking-widest text-fg-primary" suppressHydrationWarning>
              {companyName}
            </Link>

            {/* Right: CTA Buttons - Left=Contact Us (/contact), Right=Book Now (booking) */}
            <div className="flex items-center gap-3">
              {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}
                  size="sm"
                  color="primary"
                  className="font-body text-sm uppercase tracking-wide px-6 py-2 rounded-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}
                size="sm"
                color="primary"
                className="font-body text-sm uppercase tracking-wide px-6 py-2 rounded-sm"
              >
                {(props?.cta_button?.secondary_label && ctaUrls.hasSecondary) ? props.cta_button.secondary_label : (props?.cta_button?.label || "Contact")}
              </Button>
            </div>
          </div>

          {/* Navigation Row with Dropdowns - Centered */}
          <nav className="border-b border-secondary">
            <div className="flex items-center justify-center gap-8 py-4">
              {navigation.map((item: NavItem, i: number) => (
                <div
                  key={i}
                  className="relative"
                  onMouseEnter={(e) => handleMouseEnter(item, e)}
                  onMouseLeave={handleMouseLeave}
                >
                  <Link
                    href={item.href}
                    className={cx(
                      "font-body text-sm uppercase tracking-wide text-fg-primary pb-4",
                      activeDropdown === item.label && "border-b-2 border-fg-primary"
                    )}
                  >
                    {item.label}
                  </Link>
                  
                  {/* Dropdown Second Row - Horizontal Layout - Centered */}
                  {item.children && item.children.length > 0 && activeDropdown === item.label && (
                    <div 
                      className="fixed left-0 right-0 w-full pt-6 pb-6 border-b border-secondary bg-primary z-50"
                      style={{ top: `${dropdownTop}px` }}
                      onMouseEnter={handleDropdownMouseEnter}
                      onMouseLeave={handleDropdownMouseLeave}
                    >
                      <div className="mx-auto max-w-container px-4 md:px-8">
                        <div className="flex items-center justify-center gap-8">
                          {(() => {
                            const { items, showViewAll, viewAllHref, viewAllLabel } = getDropdownItems(item);
                            return (
                              <>
                                {items.map((link: NavItem, j: number) => (
                                  <Link
                                    key={j}
                                    href={link.href}
                                    className="font-body text-sm text-fg-primary hover:underline whitespace-nowrap"
                                  >
                                    {link.label}
                                  </Link>
                                ))}
                                {showViewAll && (
                                  <Link
                                    href={viewAllHref}
                                    className="font-body text-sm text-fg-primary hover:underline whitespace-nowrap font-semibold"
                                  >
                                    {viewAllLabel} →
                                  </Link>
                                )}
                              </>
                            );
                          })()}
                        </div>
                      </div>
                    </div>
                  )}
                </div>
              ))}
            </div>
          </nav>
        </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-xl font-normal uppercase tracking-widest 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-xl font-normal uppercase tracking-widest 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, showViewAll, viewAllHref, viewAllLabel } = getDropdownItems(item);
                  return (
                    <li key={i}>
                      <Link
                        href={item.href}
                        className="block font-body text-base text-fg-primary py-2"
                        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>
                          ))}
                          {showViewAll && (
                            <li>
                              <Link
                                href={viewAllHref}
                                className="block font-body text-sm text-tertiary py-1 font-semibold"
                                onClick={() => setIsMobileMenuOpen(false)}
                              >
                                {viewAllLabel} →
                              </Link>
                            </li>
                          )}
                        </ul>
                      )}
                    </li>
                  );
                })}
              </ul>
            </nav>

            {/* Mobile Menu Footer - Left=Contact Us, Right=Book Now */}
            <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}
                    target={props.cta_button.secondary_target}
                    rel={props.cta_button.secondary_target === '_blank' ? 'noopener noreferrer' : undefined}
                    color="primary"
                    className="w-full font-body text-sm uppercase tracking-wide py-3 rounded-sm"
                    onClick={() => setIsMobileMenuOpen(false)}
                  >
                    {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="w-full font-body text-sm uppercase tracking-wide py-3 rounded-sm"
                  onClick={() => setIsMobileMenuOpen(false)}
                >
                  {(props?.cta_button?.secondary_label && ctaUrls.hasSecondary) ? props.cta_button.secondary_label : (props?.cta_button?.label || "Contact")}
                </Button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Sticky Contact Button (Mobile) - Left=Contact Us, Right=Book Now */}
      <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-gray-700"
                    >
                      {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', 'aman', HeaderNavigation);
