import { Tabs as TabsPrimitive } from '@imwebme/zynk-react-components'
import tw, { TwStyle } from 'twin.macro'
import { createContext, useContext } from 'react'

type VariantType = 'line' | 'segment'
type VariantMapType = {
  [key in VariantType]: TwStyle
}

const VariantContext = createContext<VariantType | undefined>(undefined)

export interface RootProps
  extends React.ComponentProps<typeof TabsPrimitive.Root> {
  variant?: VariantType
}
const Root = ({ variant, ...props }: RootProps) => (
  <VariantContext.Provider value={variant}>
    <TabsPrimitive.Root {...props}>{props.children}</TabsPrimitive.Root>
  </VariantContext.Provider>
)

const LIST_VARIANT_STYLE_MAP: VariantMapType = {
  line: tw``,
  segment: tw``,
}
type ListProps = React.ComponentProps<typeof TabsPrimitive.List>
const List = (props: ListProps) => {
  const variant = useContext(VariantContext)

  return (
    <TabsPrimitive.List
      {...props}
      css={[
        tw`
          p-0
          bg-transparent
          dark:bg-transparent
        `,
        variant && LIST_VARIANT_STYLE_MAP[variant],
      ]}
    >
      {props.children}
    </TabsPrimitive.List>
  )
}

const TRIGGER_VARIANT_STYLE: VariantMapType = {
  line: tw`
    data-[state=active]:relative
    data-[state=active]:after:content-['']
    data-[state=active]:after:h-[2px]
    data-[state=active]:after:bg-semantic-focus
    data-[state=active]:after:absolute
    data-[state=active]:after:bottom-0
    data-[state=active]:after:left-0
    data-[state=active]:after:right-0
    data-[state=active]:text-semantic-focus
    data-[state=active]:bg-transparent
    data-[state=active]:shadow-none
  `,
  segment: tw`
    text-semantic-text-sub
    shadow-none
    rounded-[6px]
    data-[state=active]:shadow-none
    data-[state=active]:text-white
    data-[state=active]:bg-semantic-focus
  `,
}

type TriggerProps = React.ComponentProps<typeof TabsPrimitive.Trigger>
const Trigger = (props: TriggerProps) => {
  const variant = useContext(VariantContext)

  return (
    <TabsPrimitive.Trigger
      {...props}
      css={[
        tw`
          rounded-none
          bg-transparent
          dark:text-dark-semantic-text
          dark:data-[state=active]:bg-transparent
          dark:data-[state=active]:text-dark-semantic-focus
        `,
        TRIGGER_VARIANT_STYLE[variant as VariantType],
      ]}
    >
      {props.children}
    </TabsPrimitive.Trigger>
  )
}

const Content = TabsPrimitive.Content

export {
  Root,
  List,
  Trigger,
  Content,
  TRIGGER_VARIANT_STYLE as TRIGGER_VARIANT_MAP,
}
