import { Slot } from '@radix-ui/react-slot'
import * as TabsPrimitive from '@radix-ui/react-tabs'

import { cva, type VariantProps } from 'class-variance-authority'
import type { ComponentProps } from 'react'

import { cn } from '@lib/utils'

function Tabs({ className, ...props }: ComponentProps<typeof TabsPrimitive.Root>) {
  return <TabsPrimitive.Root data-slot="tabs" className={cn('flex flex-col gap-2', className)} {...props} />
}

const tabsListVariants = cva('w-fit text-muted-foreground inline-flex items-center justify-center rounded-lg', {
  variants: {
    variant: {
      default: 'bg-muted p-[3px]',
      protocol: 'bg-transparent',
    },
    size: {
      default: 'h-9',
      sm: 'h-6',
      lg: 'h-10',
    },
  },
  defaultVariants: {
    variant: 'default',
    size: 'default',
  },
})

function TabsList({
  className,
  variant,
  size,
  asChild = false,
  ...props
}: ComponentProps<typeof TabsPrimitive.List> & VariantProps<typeof tabsListVariants> & { asChild?: boolean }) {
  const Comp = asChild ? Slot : TabsPrimitive.List
  return <Comp data-slot="tabs-list" className={cn(tabsListVariants({ variant, size, className }))} {...props} />
}

const tabsTriggerVariants = cva(
  "h-[100%] text-lg inline-flex items-center justify-center gap-1.5 font-medium whitespace-nowrap focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 text-foreground",
  {
    variants: {
      variant: {
        default:
          'h-[calc(100%-1px)] flex-1 rounded-md border border-transparent px-2 py-1 transition-[color,box-shadow] dark:text-muted-foreground data-[state=active]:bg-background dark:data-[state=active]:text-foreground dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 data-[state=active]:shadow-sm',
        protocol:
          'bg-transparent border-b-2 border-b-transparent hover:text-primary hover:border-b-primary data-[state=active]:border-b-primary data-[state=active]:text-primary',
      },
    },
  },
)

function TabsTrigger({
  className,
  variant,
  asChild = false,
  ...props
}: ComponentProps<typeof TabsPrimitive.Trigger> & VariantProps<typeof tabsTriggerVariants> & { asChild?: boolean }) {
  const Comp = asChild ? Slot : TabsPrimitive.Trigger
  return <Comp data-slot="tabs-trigger" className={cn(tabsTriggerVariants({ variant, className }))} {...props} />
}

function TabsContent({ className, ...props }: ComponentProps<typeof TabsPrimitive.Content>) {
  return <TabsPrimitive.Content data-slot="tabs-content" className={cn('flex-1 outline-none', className)} {...props} />
}

export { Tabs, TabsList, TabsTrigger, TabsContent }
