"use client"

import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
import { useSemanticColors } from "@/contexts/semantic-color-context"
import type { SemanticColorName } from "@/utils/semantic-colors"

const alertVariants = cva(
  "relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground",
  {
    variants: {
      variant: {
        success: "",
        warning: "",
        error: "",
        info: "",
        neutral: "",
      },
    },
    defaultVariants: {
      variant: "neutral",
    },
  },
)

export interface SemanticAlertProps extends React.HTMLAttributes<HTMLDivElement>, VariantProps<typeof alertVariants> {
  variant?: SemanticColorName
}

const SemanticAlert = React.forwardRef<HTMLDivElement, SemanticAlertProps>(
  ({ className, variant = "neutral", style, ...props }, ref) => {
    const { getSemanticColorVar } = useSemanticColors()

    const semanticStyle = {
      backgroundColor: getSemanticColorVar(variant, "bg"),
      borderColor: getSemanticColorVar(variant, "border"),
      ...style,
    }

    return (
      <div
        ref={ref}
        role="alert"
        className={cn(alertVariants({ variant }), className)}
        style={semanticStyle}
        {...props}
      />
    )
  },
)
SemanticAlert.displayName = "SemanticAlert"

const SemanticAlertTitle = React.forwardRef<
  HTMLParagraphElement,
  React.HTMLAttributes<HTMLHeadingElement> & { variant?: SemanticColorName }
>(({ className, variant = "neutral", style, ...props }, ref) => {
  const { getSemanticColorVar } = useSemanticColors()

  const semanticStyle = {
    color: getSemanticColorVar(variant, "text"),
    ...style,
  }

  return (
    <h5
      ref={ref}
      className={cn("mb-1 font-medium leading-none tracking-tight", className)}
      style={semanticStyle}
      {...props}
    />
  )
})
SemanticAlertTitle.displayName = "SemanticAlertTitle"

const SemanticAlertDescription = React.forwardRef<
  HTMLParagraphElement,
  React.HTMLAttributes<HTMLParagraphElement> & { variant?: SemanticColorName }
>(({ className, variant = "neutral", style, ...props }, ref) => {
  const { getSemanticColorVar } = useSemanticColors()

  const semanticStyle = {
    color: getSemanticColorVar(variant, "text"),
    opacity: 0.8,
    ...style,
  }

  return <div ref={ref} className={cn("text-sm [&_p]:leading-relaxed", className)} style={semanticStyle} {...props} />
})
SemanticAlertDescription.displayName = "SemanticAlertDescription"

export { SemanticAlert, SemanticAlertTitle, SemanticAlertDescription }
