"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';

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 closeTimeoutRef = useRef<NodeJS.Timeout | null>(null);
  
  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 || '';
  
  const navigation = navigationOverride || config?.navigation?.header || [];
  const ctaUrls = resolveCtaUrls(companyInformation, props?.cta_button, {
    primaryHrefOverride: props?.primaryHrefOverride,
    secondaryHrefOverride: props?.secondaryHrefOverride,
  });

  const cancelCloseTimeout = useCallback(() => {
    if (closeTimeoutRef.current) {
      clearTimeout(closeTimeoutRef.current);
      closeTimeoutRef.current = null;
    }
  }, []);

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

  const handleMouseLeave = useCallback(() => {
    cancelCloseTimeout();
    closeTimeoutRef.current = setTimeout(() => {
      setActiveDropdown(null);
    }, 150);
  }, [cancelCloseTimeout]);

  const handleDropdownMouseEnter = useCallback(() => {
    cancelCloseTimeout();
  }, [cancelCloseTimeout]);

  const handleDropdownMouseLeave = useCallback(() => {
    handleMouseLeave();
  }, [handleMouseLeave]);

  return (
    <>
      {/* Desktop Header */}
      <header className="hidden md:block sticky top-0 z-50 bg-primary" style={{ borderBottom: '3px solid rgb(217, 191, 168)' }}>
        <div className="mx-auto max-w-container px-4 md:px-8">
          <div className="relative flex items-center justify-between py-5">
            {/* Left: Logo only */}
            <Link href="/" className="flex items-center z-10">
              {logoUrl ? (
                <Image 
                  src={logoUrl} 
                  alt={companyName}
                  className="h-12 w-auto object-contain"
                  width={180}
                  height={48}
                />
              ) : (
                <div className="flex flex-col">
                  <span className="font-display text-2xl font-normal" style={{ color: 'rgb(148, 102, 76)' }}>
                    {companyName}
                  </span>
                  <span className="font-body text-xs tracking-widest uppercase" style={{ color: 'rgb(148, 102, 76)', opacity: 0.7 }}>
                    Concierge Cosmetic Injections
                  </span>
                </div>
              )}
            </Link>

            {/* Center: Navigation - absolutely positioned to center in full width */}
            <nav className="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 flex items-center gap-1">
              {navigation.map((item) => (
                <div
                  key={item.label}
                  className="relative"
                  onMouseEnter={() => handleMouseEnter(item)}
                  onMouseLeave={handleMouseLeave}
                >
                  {item.href ? (
                    <Link
                      href={item.href}
                      className="font-display text-xl font-semibold px-5 py-2"
                      style={{ color: 'rgb(170, 143, 123)' }}
                    >
                      {item.label}
                    </Link>
                  ) : (
                    <span className="font-display text-xl font-semibold px-5 py-2 cursor-pointer" style={{ color: 'rgb(170, 143, 123)' }}>
                      {item.label}
                    </span>
                  )}

                  {/* Dropdown */}
                  {item.children && item.children.length > 0 && activeDropdown === item.label && (
                    <div
                      className="absolute left-0 top-full pt-2"
                      onMouseEnter={handleDropdownMouseEnter}
                      onMouseLeave={handleDropdownMouseLeave}
                    >
                      <div className="balance-dropdown-panel bg-primary border border-secondary shadow-md min-w-48 py-2">
                        {item.children.map((child) => (
                          <Link
                            key={child.href}
                            href={child.href}
                            className="block font-display text-sm hover:bg-secondary/10 px-4 py-2"
                            style={{ color: 'rgb(170, 143, 123)' }}
                          >
                            {child.label}
                          </Link>
                        ))}
                      </div>
                    </div>
                  )}
                </div>
              ))}
            </nav>

            {/* Right: CTA Buttons */}
            <div className="flex items-center gap-3 flex-shrink-0 z-10">
              {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" style={{ borderBottom: '3px solid rgb(217, 191, 168)' }}>
        <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="balance-mobile-menu fixed inset-0 bg-primary 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" style={{ borderBottom: '3px solid rgb(217, 191, 168)' }}>
              <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) => (
                  <li key={item.label}>
                    <Link
                      href={item.href || '#'}
                      className="block font-display text-base font-semibold py-2"
                      style={{ color: 'rgb(170, 143, 123)' }}
                      onClick={() => setIsMobileMenuOpen(false)}
                    >
                      {item.label}
                    </Link>
                    {item.children && item.children.length > 0 && (
                      <ul className="ml-4 mt-2 space-y-2">
                        {item.children.map((child) => (
                          <li key={child.href}>
                            <Link
                              href={child.href}
                              className="block font-body text-sm py-1"
                              onClick={() => setIsMobileMenuOpen(false)}
                            >
                              {child.label}
                            </Link>
                          </li>
                        ))}
                      </ul>
                    )}
                  </li>
                ))}
              </ul>
            </nav>

            {/* Mobile Menu Footer with CTA Buttons */}
            <div className="px-4 py-6" style={{ borderTop: '1px solid rgb(217, 191, 168)' }}>
              <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 Bottom Bar (mobile only) */}
      <div className="fixed bottom-0 left-0 right-0 z-40 md:hidden" style={{ backgroundColor: 'rgb(148, 133, 84)' }}>
        <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"
              style={{ borderRight: '1px solid rgba(255, 255, 255, 0.2)' }}
            >
              {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', 'balance', HeaderNavigation);
