'use client'

import * as TabsPrimitive from '@radix-ui/react-tabs'
import * as React from 'react'
import { cn } from '../../utils'
import { typographyVariants } from '../Typography'

const NavTabs = TabsPrimitive.Root

NavTabs.displayName = 'NavTabs'

type NavTabsTitleProps = React.HTMLAttributes<HTMLDivElement> & {
  children: React.ReactNode
  ref?: React.Ref<HTMLDivElement>
}

const NavTabsTitle = ({
  className,
  children,
  ref,
  ...props
}: NavTabsTitleProps) => (
  <div
    ref={ref}
    className={cn('flex items-center gap-8', className)}
    {...props}
  >
    <div className={typographyVariants({ variant: 'h3' })}>{children}</div>
    <div className="h-10 w-px shrink-0 bg-border" />
  </div>
)
NavTabsTitle.displayName = 'NavTabsTitle'

type NavTabsListProps = React.ComponentPropsWithoutRef<
  typeof TabsPrimitive.List
> & {
  indicatorOffset?: number
  ref?: React.Ref<React.ElementRef<typeof TabsPrimitive.List>>
}

const NavTabsList = ({
  className,
  children,
  indicatorOffset = 22,
  ref,
  ...props
}: NavTabsListProps) => {
  const [indicatorStyle, setIndicatorStyle] =
    React.useState<React.CSSProperties>({
      opacity: 0,
      left: 0,
    })
  const internalRef = React.useRef<HTMLDivElement>(null)

  React.useImperativeHandle(ref, () => internalRef.current!)

  const updateIndicatorPosition = React.useCallback(() => {
    if (!internalRef.current) return

    const activeElement = internalRef.current.querySelector(
      '[data-state="active"]',
    ) as HTMLElement
    if (activeElement) {
      const listRect = internalRef.current.getBoundingClientRect()
      const tabRect = activeElement.getBoundingClientRect()
      const leftPosition =
        tabRect.left - listRect.left + tabRect.width / 2 - 8.5

      setIndicatorStyle({
        opacity: 1,
        left: leftPosition,
        transition: 'all 0.2s ease-in-out',
      })
    }
  }, [])

  React.useEffect(() => {
    const observer = new MutationObserver(() => {
      updateIndicatorPosition()
    })

    if (internalRef.current) {
      observer.observe(internalRef.current, {
        attributes: true,
        attributeFilter: ['data-state'],
        subtree: true,
      })

      setTimeout(updateIndicatorPosition, 0)
    }

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

  React.useEffect(() => {
    const handleResize = () => updateIndicatorPosition()
    window.addEventListener('resize', handleResize)
    return () => window.removeEventListener('resize', handleResize)
  }, [updateIndicatorPosition])

  return (
    <TabsPrimitive.List
      ref={internalRef}
      className={cn(
        'relative inline-flex items-center justify-center gap-6 border-0',
        className,
      )}
      {...props}
    >
      <div
        className="pointer-events-none absolute z-10"
        style={{
          ...indicatorStyle,
          top: `-${indicatorOffset}px`,
        }}
      >
        <svg
          width="17"
          height="6"
          viewBox="0 0 17 6"
          fill="none"
          xmlns="http://www.w3.org/2000/svg"
        >
          <path d="M8.5 6L0.5 8.25931e-07L16.5 0L8.5 6Z" fill="var(--brand)" />
        </svg>
      </div>

      {children}
    </TabsPrimitive.List>
  )
}
NavTabsList.displayName = 'NavTabsList'

type NavTabsTriggerProps = React.ComponentPropsWithoutRef<
  typeof TabsPrimitive.Trigger
> & {
  ref?: React.Ref<React.ElementRef<typeof TabsPrimitive.Trigger>>
}

const NavTabsTrigger = ({ className, ref, ...props }: NavTabsTriggerProps) => (
  <TabsPrimitive.Trigger
    ref={ref}
    data-slot="nav-tabs-trigger"
    className={cn(
      typographyVariants({
        variant: 'body-l',
        className:
          'text-muted-more-foreground data-[state=active]:text-foreground',
      }),
      'inline-flex items-center justify-center whitespace-nowrap border-0 ring-offset-background transition-all',
      'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50',
      className,
    )}
    {...props}
  />
)
NavTabsTrigger.displayName = 'NavTabsTrigger'

type NavTabsContentProps = React.ComponentPropsWithoutRef<
  typeof TabsPrimitive.Content
> & {
  ref?: React.Ref<React.ElementRef<typeof TabsPrimitive.Content>>
}

const NavTabsContent = ({ className, ref, ...props }: NavTabsContentProps) => (
  <TabsPrimitive.Content
    ref={ref}
    className={cn(
      'mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2',
      className,
    )}
    {...props}
  />
)
NavTabsContent.displayName = 'NavTabsContent'

export { NavTabs, NavTabsTitle, NavTabsList, NavTabsTrigger, NavTabsContent }
