'use client'

import * as React from 'react'
import {
  SvgTaillessLineArrowExpandVerticalSort,
  SvgLineArrowBendDownRight,
} from '@chainlink/blocks-icons'
import { useIsMobile, useIsTablet } from '../../hooks/MediaQueries'
import { cn } from '../../utils'
import type {
  CollapsibleBreadcrumbItemProps,
  CollapsibleBreadcrumbProps,
} from '../Breadcrumb'
import {
  Drawer,
  DrawerClose,
  DrawerTrigger,
  DrawerTitle,
} from '../Drawer/Drawer'
import { useSidebarContext, SidebarTrigger } from '../Navigation'
import {
  HeaderNavTabs,
  type HeaderNavTabsProps,
} from '../NavTabs/HeaderNavTabs'
import { Typography, typographyVariants } from '../Typography'
import { MobileMenuDrawerContent } from './MobileMenuDrawerContent'

// Scroll context for header border visibility
const ScrollContext = React.createContext<{ isScrolled: boolean }>({
  isScrolled: false,
})

/**
 * Shared styles for transparent header triggers (buttons, dropdowns, etc.)
 * Used in PageHeader and other header components for consistent styling.
 */
export const transparentTriggerStyles = cn(
  'bg-foreground/[0.03]',
  'border-solid border-border border-transparent',
  'hover:border-border-hover hover:!bg-foreground/[0.03]',
  'data-[state=open]:border-border-active data-[state=open]:bg-background',
  'hover:data-[state=open]:!border-border-active hover:data-[state=open]:!bg-background',
  'focus-visible:!border-border-active focus-visible:!outline-none focus-visible:!ring-0',
  '[transition:background-color_100ms_ease-linear]',
)

type PageHeaderSpacingProps =
  | {
      reserveSpace?: 'sibling'
      spacerClassName?: never
    }
  | {
      reserveSpace: 'spacer'
      spacerClassName?: string
    }
  | {
      reserveSpace: 'none'
      spacerClassName?: never
    }

export type PageHeaderProps = React.HTMLAttributes<HTMLElement> &
  PageHeaderSpacingProps

type PageHeaderPropsWithRef = PageHeaderProps & {
  ref?: React.Ref<HTMLElement>
}

const PageHeader = ({
  className,
  children,
  reserveSpace = 'sibling',
  spacerClassName: _spacerClassName,
  ref,
  ...props
}: PageHeaderPropsWithRef) => {
  const isInsideSidebar = Boolean(useSidebarContext())
  const [isScrolled, setIsScrolled] = React.useState(false)
  const sentinelRef = React.useRef<HTMLDivElement>(null)
  const spacerClassName =
    reserveSpace === 'spacer' ? _spacerClassName : undefined

  React.useEffect(() => {
    const observer = new IntersectionObserver(
      ([entry]) => {
        setIsScrolled(!entry.isIntersecting)
      },
      {
        root: null, // Use viewport as root
        rootMargin: '0px',
        threshold: 0,
      },
    )

    const sentinel = sentinelRef.current
    if (sentinel) {
      observer.observe(sentinel)
    }

    return () => {
      observer.disconnect()
    }
  }, [])

  return (
    <ScrollContext.Provider value={{ isScrolled }}>
      <header
        ref={ref}
        data-slot="page-header"
        className={cn(
          'fixed left-0 right-0 top-0 z-[13] min-h-[74px] border-b border-transparent bg-background/[0.01] backdrop-blur-lg',
          'flex items-center gap-2 px-4 py-4 lg:px-10 lg:py-4',
          'w-full',
          isInsideSidebar &&
            'lg:left-[var(--sidebar-width-icon)] lg:w-[calc(100%_-_var(--sidebar-width-icon))]',
          isScrolled && 'border-border',
          className,
        )}
        {...props}
      >
        {isInsideSidebar && (
          <SidebarTrigger
            data-slot="page-header-sidebar-trigger"
            className={cn('size-8 p-1 lg:hidden', transparentTriggerStyles)}
          />
        )}
        {children}
      </header>
      {/* Spacer Mode: Render a visible spacer div */}
      {reserveSpace === 'spacer' && (
        <div
          className={cn(
            'w-full shrink-0',
            'h-[var(--page-header-height)]',
            'bg-background', // Default background
            spacerClassName,
          )}
          aria-hidden="true"
        />
      )}
      {/* Sentinel element to detect scroll */}
      <div
        ref={sentinelRef}
        className={cn(
          'pointer-events-none invisible w-full',
          // In sibling mode, apply the padding to the next sibling
          reserveSpace === 'sibling' &&
            '[&_+_*]:pt-[var(--page-header-spacing)]',
          // In other modes, ensure sentinel is positioned at top of flow (height 0)
          reserveSpace !== 'sibling' && 'absolute top-0 h-px',
        )}
        aria-hidden="true"
      />
    </ScrollContext.Provider>
  )
}
PageHeader.displayName = 'PageHeader'

type PageHeaderNavTabsProps = {
  title: string
} & HeaderNavTabsProps

const ChainlinkLogoMobile = ({ className }: { className: string }) => {
  return (
    <svg
      width="21"
      height="24"
      viewBox="0 0 21 24"
      fill="none"
      xmlns="http://www.w3.org/2000/svg"
      className={className}
    >
      <path
        d="M10.392 0L0 6V18L10.392 24L20.784 18V6L10.392 0ZM16.3814 15.457L10.3939 18.9139L4.4064 15.457V8.54304L10.3939 5.08608L16.3814 8.54304V15.457Z"
        fill="#0847F7"
      />
    </svg>
  )
}

const PageHeaderTitle = ({ children }: { children: React.ReactNode }) => {
  const isMobile = useIsMobile()
  return (
    <h1
      className={cn(
        typographyVariants({
          variant: isMobile ? 'body-semi-l' : 'h3',
        }),
        'flex items-center gap-2 whitespace-nowrap',
      )}
    >
      <ChainlinkLogoMobile className="md:hidden" />
      {children}
    </h1>
  )
}

const HeaderNavTabsMobileWithMenu = ({
  title,
  links,
  path,
  renderLink,
}: PageHeaderNavTabsProps) => {
  const isTablet = useIsTablet()
  if (!isTablet) {
    return <PageHeaderTitle>{title}</PageHeaderTitle>
  }

  return (
    <Drawer>
      <DrawerTrigger>
        <PageHeaderTitle>
          {title}
          <SvgTaillessLineArrowExpandVerticalSort
            color="muted"
            className="size-3 lg:hidden"
          />
        </PageHeaderTitle>
      </DrawerTrigger>
      <MobileMenuDrawerContent>
        <DrawerTitle>{title}</DrawerTitle>
        {/* Navigation Links */}
        <div className="flex flex-col space-y-1 border-0 border-l border-solid border-border">
          {links.map((link) => {
            const isActive = path === link.href
            const LinkComponent =
              renderLink ||
              (({ href, children }) => <a href={href}>{children}</a>)

            return (
              <div key={link.href} className="relative">
                {/* Blue Indicator for Active Link */}
                {isActive && (
                  <div className="absolute left-[-2px] top-1/2 h-6 w-[3px] -translate-y-1/2 bg-brand" />
                )}

                <DrawerClose asChild>
                  <LinkComponent href={link.href}>
                    <div
                      className={cn(
                        'px-5 py-2',
                        typographyVariants({
                          variant: 'body-s',
                          color: isActive
                            ? 'platform-navigation-active'
                            : 'platform-navigation-muted',
                        }),
                      )}
                    >
                      {link.name}
                    </div>
                  </LinkComponent>
                </DrawerClose>
              </div>
            )
          })}
        </div>
      </MobileMenuDrawerContent>
    </Drawer>
  )
}

type PageHeaderBreadcrumbProps = Omit<CollapsibleBreadcrumbProps, 'items'> & {
  items: Required<CollapsibleBreadcrumbItemProps>[]
}

const HeaderBreadcrumbMobileWithMenu = ({
  items,
  renderLink,
}: Pick<PageHeaderBreadcrumbProps, 'items' | 'renderLink'>) => {
  const isTablet = useIsTablet()
  if (!isTablet) {
    return null
  }

  return (
    <Drawer>
      <DrawerTrigger>
        <PageHeaderTitle>
          {items[0]?.label}
          <SvgTaillessLineArrowExpandVerticalSort
            color="muted"
            className="size-3 lg:hidden"
          />
        </PageHeaderTitle>
      </DrawerTrigger>
      <MobileMenuDrawerContent>
        {renderLink ? (
          renderLink({
            href: items[0].href,
            children: items[0].label,
            className: typographyVariants({ variant: 'body-semi-s' }),
          })
        ) : (
          <a
            href={items[0].href}
            className={typographyVariants({ variant: 'body-semi-s' })}
          >
            {items[0].label}
          </a>
        )}
        {/* Navigation Links */}
        <div className="flex flex-col space-y-4">
          {items.slice(1).map((item, index) => {
            const isLastItem = index === items.slice(1).length - 1

            if (isLastItem) {
              return (
                <DrawerClose key={item.href} asChild>
                  <div
                    className={typographyVariants({
                      variant: 'body-s',
                      className: 'flex cursor-pointer items-center gap-4',
                    })}
                  >
                    <SvgLineArrowBendDownRight color="brand" />
                    {item.label}
                  </div>
                </DrawerClose>
              )
            }

            return (
              <DrawerClose key={item.href} asChild>
                {renderLink ? (
                  renderLink({
                    href: item.href,
                    className:
                      'flex text-sm text-muted-foreground items-center gap-4',
                    // }),
                    children: (
                      <>
                        <SvgLineArrowBendDownRight color="muted" />
                        {item.label}
                      </>
                    ),
                  })
                ) : (
                  <a
                    className={typographyVariants({
                      variant: 'body-s',
                      color: 'muted',
                      className: 'flex items-center gap-4',
                    })}
                    href={item.href}
                  >
                    <SvgLineArrowBendDownRight color="muted" />
                    {item.label}
                  </a>
                )}
              </DrawerClose>
            )
          })}
        </div>
      </MobileMenuDrawerContent>
    </Drawer>
  )
}

const PageHeaderNavTabs: React.FC<PageHeaderNavTabsProps> = ({
  title,
  links,
  ...props
}) => {
  return links.length > 0 ? (
    <div className="flex h-8 flex-1 items-center gap-8">
      <HeaderNavTabsMobileWithMenu title={title} links={links} {...props} />

      <div className={'relative hidden pl-8 lg:block'}>
        <div className="absolute left-0 top-[-6px] h-10 w-[1px] bg-border" />
        <HeaderNavTabs links={links} {...props} />
      </div>
    </div>
  ) : (
    <PageHeaderTitle>{title}</PageHeaderTitle>
  )
}
PageHeaderNavTabs.displayName = 'PageHeaderNavTabs'

const PageHeaderBreadcrumb: React.FC<PageHeaderBreadcrumbProps> = ({
  items,
  renderLink,
  ...props
}) => {
  const titleItem = items[0]
  const title = titleItem?.label

  if (!title || !renderLink) {
    return null
  }

  const link = renderLink

  return (
    <div className="flex h-8 flex-1 items-center gap-8">
      <HeaderBreadcrumbMobileWithMenu items={items} {...props} />

      <div className="hidden items-center gap-2 lg:flex">
        <PageHeaderTitle>
          {titleItem?.href
            ? link({
                href: titleItem.href,
                label: title,
                className: cn(typographyVariants({ variant: 'h5' })),
              })
            : title}
        </PageHeaderTitle>
        {items.slice(1).map((item, index) => {
          const isLast = index === items.length - 2
          return (
            <div key={item.label} className="flex items-center gap-2">
              <Typography variant="body-semi" color="muted-more">
                /
              </Typography>
              {item.href && !isLast ? (
                link({
                  href: item.href,
                  label: item.label,
                  className: cn(
                    typographyVariants({
                      variant: 'body-semi',
                      color: 'muted-more',
                    }),
                  ),
                })
              ) : (
                <Typography
                  variant="body-semi"
                  color={isLast ? 'foreground' : 'muted-more'}
                >
                  {item.label}
                </Typography>
              )}
            </div>
          )
        })}
      </div>
    </div>
  )
}
PageHeaderBreadcrumb.displayName = 'PageHeaderBreadcrumb'

type PageHeaderActionsProps = React.HTMLAttributes<HTMLDivElement> & {
  ref?: React.Ref<HTMLDivElement>
}

const PageHeaderActions = ({
  className,
  children,
  ref,
  ...props
}: PageHeaderActionsProps) => {
  return (
    <div
      ref={ref}
      className={cn('ml-auto flex items-center gap-2', className)}
      {...props}
    >
      {children}
    </div>
  )
}
PageHeaderActions.displayName = 'PageHeaderActions'

export {
  PageHeader,
  PageHeaderTitle,
  PageHeaderNavTabs,
  PageHeaderActions,
  PageHeaderBreadcrumb,
  ScrollContext,
  type PageHeaderNavTabsProps,
}
