'use client'

import Link from "next/link"
import Image from "next/image"
import { ArrowSquareOut, List, ChatCircle, X, MagnifyingGlass } from "@phosphor-icons/react"
import { ThemeToggle } from "@/components/theme-toggle"
import { useMobile } from "@/lib/api-docs/mobile-context"
import { Button } from "@/components/ui/button"
import { cn } from "@/lib/utils"

// Navigation tab from config
interface NavigationTab {
  id: string
  tab: string  // Tab name (used for both navigation and page header)
  type?: 'docs' | 'openapi' | 'changelog' | 'graphql'
  path?: string
  order: number
}

// Logo config from docs.json
interface DocsLogo {
  url?: string
  alt?: string
  width?: number
  height?: number
  light?: string
  dark?: string
  href?: string  // Where logo links to (defaults to "/")
}

// Header config from docs.json
interface DocsHeaderConfig {
  showSearch?: boolean
  showThemeToggle?: boolean
}

// Navbar config from docs.json
interface DocsNavbarLink {
  label: string
  href: string
  external?: boolean
}

interface DocsNavbarPrimary {
  label: string
  href: string
}

interface DocsNavbar {
  links?: DocsNavbarLink[]
  primary?: DocsNavbarPrimary
}

interface DocsHeaderProps {
  navigationTabs?: NavigationTab[]
  activeTab: string
  onTabChange: (tabId: string) => void
  hasEndpoints?: boolean
  docsName?: string | null
  docsLogo?: DocsLogo | null
  docsHeader?: DocsHeaderConfig | null
  docsNavbar?: DocsNavbar | null
  docGroups?: unknown[] // Keep for backward compatibility but not used
  onSearchClick?: () => void
}

// Default logo fallback
const DEFAULT_LOGO = {
  url: 'https://cdn.prod.website-files.com/639181964f4fe88697a20a0a/67af64a5ba42bb659b8560c9_Logo%20(3).svg',
  alt: 'Logo',
  width: 80,
  height: 24,
}

export function DocsHeader({ 
  navigationTabs = [],
  activeTab, 
  onTabChange,
  docsName,
  docsLogo,
  docsHeader,
  docsNavbar,
  onSearchClick,
}: DocsHeaderProps) {
  const { 
    isMobile, 
    isLeftSidebarOpen, 
    isRightSidebarOpen,
    toggleLeftSidebar, 
    toggleRightSidebar 
  } = useMobile()
  
  // Use config values with defaults
  // Support both single URL and separate light/dark logos
  const hasLightDarkLogos = docsLogo?.light && docsLogo?.dark
  const logo = {
    url: docsLogo?.url || DEFAULT_LOGO.url,
    light: docsLogo?.light,
    dark: docsLogo?.dark,
    alt: docsLogo?.alt || DEFAULT_LOGO.alt,
    width: docsLogo?.width || DEFAULT_LOGO.width,
    height: docsLogo?.height || DEFAULT_LOGO.height,
  }
  
  const showSearch = docsHeader?.showSearch !== false // Default true
  const showThemeToggle = docsHeader?.showThemeToggle !== false // Default true
  
  const navbarLinks = docsNavbar?.links || []
  const navbarPrimary = docsNavbar?.primary

  // Use navigation tabs directly from config (already ordered)
  const tabs = navigationTabs.sort((a, b) => a.order - b.order)

  return (
    <header className="docs-header sticky top-0 z-50 bg-background border-b border-border">
      {/* Main header row */}
      <div className="flex h-14 w-full items-center justify-between px-3 sm:px-6">
        {/* Left side: Menu button (mobile) + Logo */}
        <div className="flex items-center gap-2">
          {/* Mobile menu button */}
          {isMobile && (
            <Button
              variant="ghost"
              size="icon"
              onClick={toggleLeftSidebar}
              className="docs-header-menu-button lg:hidden h-9 w-9"
              aria-label={isLeftSidebarOpen ? "Close menu" : "Open menu"}
            >
              {isLeftSidebarOpen ? (
                <X className="h-5 w-5" weight="bold" />
              ) : (
                <List className="h-5 w-5" weight="bold" />
              )}
            </Button>
          )}
          
          <Link 
            href={docsLogo?.href || "/"} 
            className="docs-header-logo flex items-center gap-2 sm:gap-3 min-h-[44px] min-w-[44px] touch-manipulation"
          >
            {hasLightDarkLogos ? (
              <>
                {/* Light mode logo */}
                <Image
                  src={logo.light!}
                  alt={logo.alt}
                  width={logo.width}
                  height={logo.height}
                  className="w-auto dark:hidden pointer-events-none"
                  style={{ height: logo.height }}
                  priority
                />
                {/* Dark mode logo */}
                <Image
                  src={logo.dark!}
                  alt={logo.alt}
                  width={logo.width}
                  height={logo.height}
                  className="w-auto hidden dark:block pointer-events-none"
                  style={{ height: logo.height }}
                  priority
                />
              </>
            ) : (
              <Image
                src={logo.url}
                alt={logo.alt}
                width={logo.width}
                height={logo.height}
                className="w-auto dark:invert pointer-events-none"
                style={{ height: logo.height }}
                priority
              />
            )}
            {docsName && (
              <>
                <div className="hidden sm:block h-5 w-px bg-border" />
                <span className="docs-header-title hidden sm:inline text-sm font-medium text-muted-foreground pointer-events-none">
                  {docsName}
                </span>
              </>
            )}
          </Link>
        </div>
        
        {/* Center: Search bar */}
        {showSearch && (
          <div className="docs-header-search hidden md:flex flex-1 max-w-md mx-6">
            <button
              onClick={onSearchClick}
              className="relative w-full flex items-center gap-2 px-3 h-9 bg-muted/50 border border-border rounded-md text-sm text-muted-foreground hover:bg-muted/70 transition-colors"
            >
              <MagnifyingGlass className="h-4 w-4" />
              <span className="flex-1 text-left">Search...</span>
              <kbd className="pointer-events-none hidden sm:inline-flex h-5 select-none items-center gap-1 rounded border bg-muted px-1.5 font-mono text-[10px] font-medium">
                ⌘K
              </kbd>
            </button>
          </div>
        )}
        
        {/* Right side: Nav items + Primary button + Theme toggle */}
        <div className="flex items-center gap-1 sm:gap-2">
          {/* Navbar links from config */}
          {navbarLinks.length > 0 && (
            <nav className="docs-header-nav hidden lg:flex items-center gap-1">
              {navbarLinks.map((link) => (
                <Link
                  key={link.href}
                  href={link.href}
                  className="docs-header-nav-link flex items-center gap-1.5 px-3 py-1.5 text-sm text-muted-foreground hover:text-foreground hover:bg-muted/50 rounded-sm transition-colors"
                  {...(link.external && { target: "_blank", rel: "noopener noreferrer" })}
                >
                  <span>{link.label}</span>
                  {link.external && <ArrowSquareOut className="h-3.5 w-3.5" weight="bold" />}
                </Link>
              ))}
            </nav>
          )}
          
          {/* Primary button from config */}
          {navbarPrimary && (
            <Button asChild size="sm" className="docs-header-button docs-button-primary hidden sm:flex">
              <Link href={navbarPrimary.href}>
                {navbarPrimary.label}
              </Link>
            </Button>
          )}
          
          {showThemeToggle && <ThemeToggle />}
          
          {/* Mobile agent button */}
          {isMobile && (
            <Button
              variant="ghost"
              size="icon"
              onClick={toggleRightSidebar}
              className="docs-header-button lg:hidden h-9 w-9"
              aria-label={isRightSidebarOpen ? "Close assistant" : "Open assistant"}
            >
              {isRightSidebarOpen ? (
                <X className="h-5 w-5" weight="bold" />
              ) : (
                <ChatCircle className="h-5 w-5" weight="fill" />
              )}
            </Button>
          )}
        </div>
      </div>
      
      {/* Sub-header with tabs */}
      {tabs.length > 0 && (
        <div className="docs-tabs flex items-center px-3 sm:px-6 border-y border-border overflow-x-auto overflow-y-visible bg-muted/50 dark:bg-muted/20">
          {tabs.map((t) => (
            <button
              key={t.id}
              onClick={() => onTabChange(t.id)}
              className={cn(
                'docs-tab relative px-4 py-2.5 text-sm font-medium whitespace-nowrap transition-colors',
                activeTab === t.id
                  ? 'docs-tab-active text-foreground font-semibold'
                  : 'text-muted-foreground hover:text-foreground'
              )}
            >
              {t.tab}
              {/* Active indicator line */}
              {activeTab === t.id && (
                <span 
                  className="absolute bottom-0 left-0 right-0 h-[2px] rounded-full bg-primary z-10"
                />
              )}
            </button>
          ))}
        </div>
      )}
    </header>
  )
}
