import * as React from 'react'
import tw, { TwStyle } from 'twin.macro'

const PRIMARY_STYLE = tw`
relative w-full rounded-lg border p-4 [&>svg]:absolute [&>svg]:text-foreground [&>svg]:left-4 [&>svg]:top-4 [&>svg+div]:translate-y-[-3px] [&:has(svg)]:pl-11
`
type VariantType = 'default' | 'destructive'
const VARIANT_MAP = {
  default: tw`bg-background text-foreground`,
  destructive: tw`text-destructive border-destructive/50 dark:border-destructive [&>svg]:text-destructive text-destructive`,
} satisfies Record<VariantType, TwStyle>

interface AlertProps extends React.HTMLAttributes<HTMLDivElement> {
  variant?: VariantType
}

const Alert = React.forwardRef<
  HTMLDivElement,
  React.HTMLAttributes<HTMLDivElement> & AlertProps
>(({ variant = 'default', ...props }, ref) => (
  <div
    ref={ref}
    role="alert"
    css={[PRIMARY_STYLE, VARIANT_MAP[variant]]}
    {...props}
  />
))
Alert.displayName = 'Alert'

const AlertTitle = React.forwardRef<
  HTMLParagraphElement,
  React.HTMLAttributes<HTMLHeadingElement>
>(({ ...props }, ref) => (
  <h5 ref={ref} tw="mb-1 font-medium leading-none tracking-tight" {...props} />
))
AlertTitle.displayName = 'AlertTitle'

const AlertDescription = React.forwardRef<
  HTMLParagraphElement,
  React.HTMLAttributes<HTMLParagraphElement>
>(({ ...props }, ref) => (
  <div ref={ref} tw="text-sm [&_p]:leading-relaxed" {...props} />
))
AlertDescription.displayName = 'AlertDescription'

export { Alert as Root, AlertTitle as Title, AlertDescription as Description }
