"use client"
import { motion } from "motion/react"
import React, { ComponentPropsWithoutRef, ElementRef, forwardRef } from "react"
import { tv, type VariantProps } from "tailwind-variants"
import { classNames } from "../../utils/classNames"
import { Item, ItemProps } from "../Item"
import { NamespacedLayoutGroup } from "../NamespacedLayoutGroup"
import { Text, TextBodyProps } from "../Text"

export type TabMenuProps = ComponentPropsWithoutRef<"nav">

const TabMenuBase = forwardRef<ElementRef<"div">, TabMenuProps>(
  function TabMenu({ children, className, ...rest }, ref) {
    return (
      <NamespacedLayoutGroup>
        <nav
          className={classNames("flex gap-6", className)}
          ref={ref}
          {...rest}
        >
          {children}
        </nav>
      </NamespacedLayoutGroup>
    )
  },
)

const tabMenuItemVariants = tv({
  base: "relative w-fit whitespace-nowrap pb-2 font-normal text-text-secondary hover:text-text-primary focus-visible:text-text-primary focus-visible:outline-hidden",
  variants: {
    size: {
      sm: "pt-1",
      md: "pt-1.5",
    },
    active: {
      true: "font-medium text-text-primary",
    },
  },
})

export type TabMenuItemProps = ItemProps &
  VariantProps<typeof tabMenuItemVariants>

const TabMenuItemBase = forwardRef<ElementRef<typeof Item>, TabMenuItemProps>(
  function TabMenuItem(
    { className, active, size = "md", children, ...rest },
    ref,
  ) {
    return (
      <Item
        aria-current={active ? "page" : undefined}
        className={classNames(tabMenuItemVariants({ active, size }), className)}
        ref={ref}
        variant="unstyled"
        {...rest}
      >
        {children}

        {active && (
          <motion.div
            className="absolute left-0 top-0 flex size-full items-end justify-center"
            layoutId="tab"
            // https://github.com/framer/motion/issues/1535#issuecomment-1574354617
            style={{ originY: "top" }}
            transition={{
              type: "spring",
              duration: 0.4,
              bounce: 0,
            }}
          >
            <span className="z-0 h-0.5 w-full bg-text-primary"></span>
          </motion.div>
        )}
      </Item>
    )
  },
)

const TabMenuItemTitle = forwardRef<
  ElementRef<typeof Text.Heading>,
  TextBodyProps
>(function TabMenuItemTitle({ className, ...rest }, ref) {
  return (
    <Text.Body
      className={classNames("relative font-inherit", className)}
      ref={ref}
      size="sm"
      {...rest}
    />
  )
})

export const TabMenuItem = Object.assign(TabMenuItemBase, {
  Title: TabMenuItemTitle,
})

export const TabMenu = Object.assign(TabMenuBase, {
  Item: TabMenuItem,
})
