'use client';
import React, { useRef, useState } from 'react';
import Link from 'next/link';
import Image from 'next/image';
import { ChevronDown } from "@untitledui/icons";
import { Button as AriaButton, Dialog as AriaDialog, DialogTrigger as AriaDialogTrigger, Popover as AriaPopover } from "react-aria-components";
import { Button } from '../elements';
import { GenericHeaderComponent } from './generic-header-component';
import { cx } from '../../utils/cx';
import { getLogoUrl } from '../../utils/photo-helpers';
import type { CompanyInformation } from '../../types/api/company-information';
import type { WebsitePhotos } from '../../types/api/website-photos';
import type { NavItem, SiteConfig } from '../../types/config';
import { resolveCtaUrls, isExternalCtaUrl } from '../../lib/cta-urls';

export interface HeaderProps {
  logo: {
    text: string;
    href: string;
    image?: string;
  };
  cta_button?: {
    label: string;
    href: string;
    target?: '_blank' | '_self';
    secondary_label?: string;
    secondary_href?: string;
    secondary_target?: '_blank' | '_self';
  };
  /** When set, overrides the default primary CTA URL (booking or /contact). */
  primaryHrefOverride?: string | null;
  /** When set, overrides the default secondary CTA URL (/contact). */
  secondaryHrefOverride?: string | null;
}

export interface HeaderComponentProps {
  variant?: 'minimal' | 'centered' | 'standard';
  props?: HeaderProps;
  navigation?: NavItem[];
  logoImage?: string;
  logoText?: string;
  config?: SiteConfig;
  companyInformation?: CompanyInformation | null;
  websitePhotos?: WebsitePhotos | null;
}

const MobileNavItem = ({ label, href, children, onClose }: { 
  label: string; 
  href?: string; 
  children?: React.ReactNode;
  onClose?: () => void;
}) => {
  const [isOpen, setIsOpen] = useState(false);

  if (href) {
    return (
      <li>
        <Link 
          href={href} 
          className="flex items-center justify-between px-4 py-3 text-sm font-medium text-primary hover:bg-primary_hover"
          onClick={onClose}
        >
          {label}
        </Link>
      </li>
    );
  }

  return (
    <li className="flex flex-col gap-0.5">
      <button
        aria-expanded={isOpen}
        onClick={() => setIsOpen(!isOpen)}
        className="flex w-full items-center justify-between px-4 py-3 text-sm font-medium text-primary hover:bg-primary_hover"
      >
        {label}
        <ChevronDown
          className={cx("size-4 stroke-[2.625px] text-fg-quaternary transition duration-100 ease-linear", isOpen ? "-rotate-180" : "rotate-0")}
        />
      </button>
      {isOpen && <div>{children}</div>}
    </li>
  );
};

export function HeaderNavigation({ 
  variant = 'standard', 
  props, 
  navigation: navigationOverride, 
  logoImage: logoImageOverride, 
  logoText: logoTextOverride, 
  config,
  companyInformation,
  websitePhotos,
}: HeaderComponentProps) {
  const headerRef = useRef<HTMLElement>(null);
  
  // Use navigation from config or override
  const navigation = navigationOverride || config?.navigation?.header || [];
  
  // Build logo
  const logoImage = logoImageOverride || getLogoUrl(websitePhotos) || props?.logo?.image;
  const logoText = logoTextOverride || companyInformation?.company_name || props?.logo?.text || '';
  const cta_button = props?.cta_button;
  const ctaUrls = resolveCtaUrls(companyInformation, cta_button, {
    primaryHrefOverride: props?.primaryHrefOverride,
    secondaryHrefOverride: props?.secondaryHrefOverride,
  });
  
  const logo = {
    text: logoText || '',
    href: props?.logo?.href || '/',
    image: logoImage,
  };
  
  const dynamicNavigation = navigation;

  const getVariantClasses = () => {
    switch (variant) {
      case 'minimal':
        return 'py-4';
      case 'centered':
        return 'py-6';
      case 'standard':
      default:
        return 'py-4';
    }
  };

  const HoverDropdown = ({ label, href, children }: { label: string; href?: string; children: React.ReactNode }) => {
    const [isOpen, setIsOpen] = useState(false);
    const timeoutRef = React.useRef<NodeJS.Timeout | null>(null);

    const handleMouseEnter = () => {
      if (timeoutRef.current) {
        clearTimeout(timeoutRef.current);
        timeoutRef.current = null;
      }
      setIsOpen(true);
    };

    const handleMouseLeave = () => {
      const id = setTimeout(() => {
        setIsOpen(false);
      }, 100);
      timeoutRef.current = id;
    };

    React.useEffect(() => {
      return () => {
        if (timeoutRef.current) {
          clearTimeout(timeoutRef.current);
        }
      };
    }, []);

    return (
      <div 
        className="relative"
        onMouseEnter={handleMouseEnter}
        onMouseLeave={handleMouseLeave}
      >
        <Link
          href={href || '#'}
          className="flex cursor-pointer items-center gap-0.5 rounded-lg px-1.5 py-1 text-sm font-medium text-secondary outline-focus-ring transition duration-100 ease-linear hover:text-secondary_hover focus-visible:outline-2 focus-visible:outline-offset-2"
        >
          <span className="px-0.5">{label}</span>
          <ChevronDown className={cx("size-4 stroke-[2.625px] text-fg-quaternary transition duration-100 ease-linear", isOpen ? "-rotate-180" : "rotate-0")} />
        </Link>
        
        {isOpen && (
          <div 
            className="absolute top-full left-0 z-50 mt-1 origin-top animate-in fade-in slide-in-from-top-1 duration-75 ease-out"
            onMouseEnter={handleMouseEnter}
            onMouseLeave={handleMouseLeave}
          >
            <div className="w-max max-w-sm">
              {children}
            </div>
          </div>
        )}
      </div>
    );
  };

  const headerNavItems = dynamicNavigation.map((navItem) => {
    if (navItem.children && navItem.children.length > 0) {
      return {
        label: navItem.label,
        href: navItem.href,
        menu: (
          <GenericHeaderComponent 
            items={navItem.children.map(child => ({
              label: child.label,
              href: child.href,
              subtitle: child.subtitle,
            }))}
          />
        ),
      };
    }
    return {
      label: navItem.label,
      href: navItem.href,
    };
  });

  return (
    <>
    <header 
      ref={headerRef}
      className={cx(
        "sticky top-0 z-50 flex h-18 w-full items-center justify-center backdrop-blur-md bg-primary/80 md:h-20",
        getVariantClasses()
      )}
    >
      <div className="flex size-full max-w-container flex-1 items-center pr-3 pl-4 md:px-8">
        <div className="flex w-full justify-between gap-4">
          <div className="flex flex-1 items-center gap-5">
            <Link href={logo?.href || '/'} className="flex items-center space-x-2">
              {logoImage ? (
                <Image 
                  src={logoImage} 
                  alt={logoText}
                  className="h-8 w-8 object-contain"
                  width={32}
                  height={32}
                />
              ) : (
                <div className="h-8 w-8 bg-blue-600 rounded-lg flex items-center justify-center">
                  <span className="text-white font-bold text-lg">
                    {logoText?.charAt(0)?.toUpperCase() || ''}
                  </span>
                </div>
              )}
              <span className="text-xl font-bold text-primary hidden md:block">{logoText}</span>
            </Link>

            <nav className="max-md:hidden">
              <ul className="flex items-center gap-0.5">
                {headerNavItems.map((navItem) => (
                  <li key={navItem.label}>
                    {navItem.menu ? (
                      <HoverDropdown label={navItem.label} href={navItem.href}>
                        {navItem.menu}
                      </HoverDropdown>
                    ) : (
                      <Link
                        href={navItem.href || '#'}
                        className="flex cursor-pointer items-center gap-0.5 rounded-lg px-1.5 py-1 text-sm font-medium text-secondary outline-focus-ring transition duration-100 ease-linear hover:text-secondary_hover focus:outline-offset-2 focus-visible:outline-2"
                      >
                        <span className="px-0.5">{navItem.label}</span>
                      </Link>
                    )}
                  </li>
                ))}
              </ul>
            </nav>
          </div>

          <div className="hidden items-center gap-3 md:flex">
            {/* Left: Contact Us -> /contact */}
            {cta_button?.secondary_label && ctaUrls.hasSecondary && (
              <Button 
                href={ctaUrls.secondaryHref}
                target={cta_button.secondary_target}
                rel={cta_button.secondary_target === '_blank' ? 'noopener noreferrer' : undefined}
                color="secondary" 
                size="lg"
              >
                {cta_button.label}
              </Button>
            )}
            {/* Right: Book Now -> booking link (external opens in new tab) */}
            <Button 
              href={ctaUrls.primaryHref}
              target={cta_button?.target ?? (isExternalCtaUrl(ctaUrls.primaryHref) ? '_blank' : undefined)}
              rel={(cta_button?.target === '_blank' || isExternalCtaUrl(ctaUrls.primaryHref)) ? 'noopener noreferrer' : undefined}
              color="primary" 
              size="lg"
            >
              {(cta_button?.secondary_label && ctaUrls.hasSecondary) ? cta_button.secondary_label : (cta_button?.label || "Get Started")}
            </Button>
          </div>
          <AriaDialogTrigger>
            <AriaButton
              aria-label="Toggle navigation menu"
              className={({ isFocusVisible, isHovered }) =>
                cx(
                  "group ml-auto cursor-pointer rounded-lg p-2 md:hidden",
                  isHovered && "bg-primary_hover",
                  isFocusVisible && "outline-2 outline-offset-2 outline-focus-ring",
                )
              }
            >
              <svg aria-hidden="true" width="24" height="24" viewBox="0 0 24 24" fill="none">
                <path
                  className="hidden text-secondary group-aria-expanded:block"
                  d="M18 6L6 18M6 6L18 18"
                  stroke="currentColor"
                  strokeWidth="2"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                />
                <path
                  className="text-secondary group-aria-expanded:hidden"
                  d="M3 12H21M3 6H21M3 18H21"
                  stroke="currentColor"
                  strokeWidth="2"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                />
              </svg>
            </AriaButton>
            <AriaPopover
              triggerRef={headerRef}
              className="h-calc(100%-72px) scrollbar-hide w-full overflow-y-auto shadow-lg md:hidden"
              offset={0}
              crossOffset={20}
              containerPadding={0}
              placement="bottom left"
            >
              <AriaDialog className="outline-hidden">
                <nav className="w-full bg-primary shadow-lg">
                  <ul className="flex flex-col gap-0.5 py-5">
                    {headerNavItems.map((navItem) =>
                      navItem.menu ? (
                        <MobileNavItem 
                          key={navItem.label} 
                          label={navItem.label}
                        >
                          {navItem.menu}
                        </MobileNavItem>
                      ) : (
                        <MobileNavItem 
                          key={navItem.label} 
                          label={navItem.label} 
                          href={navItem.href}
                        />
                      ),
                    )}
                  </ul>

                  <div className="flex flex-col gap-3 border-t border-secondary px-4 py-6">
                    {/* Contact Us -> /contact */}
                    {cta_button?.secondary_label && ctaUrls.hasSecondary && (
                      <Button 
                        href={ctaUrls.secondaryHref}
                        target={cta_button.secondary_target}
                        rel={cta_button.secondary_target === '_blank' ? 'noopener noreferrer' : undefined}
                        color="secondary" 
                        size="lg"
                      >
                        {cta_button.label}
                      </Button>
                    )}
                    {/* Book Now -> booking link (external opens in new tab) */}
                    <Button 
                      href={ctaUrls.primaryHref}
                      target={cta_button?.target ?? (isExternalCtaUrl(ctaUrls.primaryHref) ? '_blank' : undefined)}
                      rel={(cta_button?.target === '_blank' || isExternalCtaUrl(ctaUrls.primaryHref)) ? 'noopener noreferrer' : undefined}
                      color="primary" 
                      size="lg"
                    >
                      {(cta_button?.secondary_label && ctaUrls.hasSecondary) ? cta_button.secondary_label : (cta_button?.label || "Get Started")}
                    </Button>
                  </div>
                </nav>
              </AriaDialog>
            </AriaPopover>
          </AriaDialogTrigger>
        </div>
      </div>
    </header>

      {/* Sticky Book/Contact bar (mobile only) */}
      <div className="fixed bottom-0 left-0 right-0 z-40 md:hidden bg-fg-primary">
        <div className="flex gap-0">
          {/* Left: Contact Us -> /contact */}
          {cta_button?.secondary_label && ctaUrls.hasSecondary && (
            <Button
              href={ctaUrls.secondaryHref}
              target={cta_button.secondary_target}
              rel={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"
            >
              {cta_button.label}
            </Button>
          )}
          {/* Right: Book Now -> booking link (external opens in new tab) */}
          <Button
            href={ctaUrls.primaryHref}
            target={cta_button?.target ?? (isExternalCtaUrl(ctaUrls.primaryHref) ? '_blank' : undefined)}
            rel={(cta_button?.target === '_blank' || isExternalCtaUrl(ctaUrls.primaryHref)) ? 'noopener noreferrer' : undefined}
            color="primary"
            className={`${cta_button?.secondary_label && ctaUrls.hasSecondary ? 'flex-1' : 'w-full'} font-body text-sm uppercase tracking-wide py-4 rounded-none`}
          >
            {(cta_button?.secondary_label && ctaUrls.hasSecondary) ? cta_button.secondary_label : (cta_button?.label || 'Contact')}
          </Button>
        </div>
      </div>
    </>
  );
}
