import type React from 'react'
import { type ReactNode } from 'react'
import { toast } from 'sonner'
import { SvgDelete1 } from '@chainlink/blocks-icons'
import { cn } from '../../utils'
import { Button } from '../Button'
import { typographyVariants } from '../Typography'
import { type ToastProps } from './Toast'
import type { Width } from './variants'
import { toastVariants, type Variant } from './variants'

export const ToastRoot = ({
  variant,
  children,
  width = 'default',
}: {
  variant: Variant
  width?: Width
  children: ReactNode
}) => {
  return <div className={cn(toastVariants({ variant, width }))}>{children}</div>
}

type ToastActionProps = React.ButtonHTMLAttributes<HTMLButtonElement> & {
  toastId: ToastProps['toastId']
  action: NonNullable<ToastProps['action']>
  ref?: React.Ref<HTMLButtonElement>
}

export const ToastAction = ({
  className,
  toastId,
  action,
  ref,
  ...props
}: ToastActionProps) => {
  return (
    <Button
      variant="tertiary"
      size="xs"
      width="hug"
      ref={ref}
      className={cn(className)}
      {...props}
      onClick={() => {
        action.onClick()
        toast.dismiss(toastId)
      }}
    >
      {action.label}
    </Button>
  )
}
ToastAction.displayName = 'ToastAction'

export const ToastClose = ({ toastId }: { toastId: ToastProps['toastId'] }) => (
  <button
    className={cn(
      'self-start text-foreground focus:outline-none focus:ring-2 focus:ring-ring',
    )}
    onClick={() => toast.dismiss(toastId)}
  >
    <SvgDelete1
      width="16"
      height="16"
      className={cn(
        'group-[.error]:text-error-muted-foreground group-[.info]:text-progress-muted-foreground group-[.success]:text-success-muted-foreground group-[.warning]:text-warning-muted-foreground',
      )}
    />
  </button>
)
ToastClose.displayName = 'ToastClose'

export const ToastCountdown = () => (
  <div className={cn('absolute bottom-0 right-2 h-0.5 w-full overflow-hidden')}>
    <div
      className={cn(
        'h-full w-full origin-left animate-shrink group-[.error]:bg-error-muted-foreground group-[.info]:bg-progress-muted-foreground group-[.success]:bg-success-muted-foreground group-[.warning]:bg-warning-muted-foreground',
      )}
    />
  </div>
)

export const ToastDescription = ({ children }: { children: ReactNode }) => (
  <div
    className={cn(
      typographyVariants({ variant: 'body-s', color: 'currentColor' }),
    )}
  >
    {children}
  </div>
)

export const ToastTitle = ({ children }: { children: ReactNode }) => (
  <div
    className={cn(typographyVariants({ variant: 'h6', color: 'currentColor' }))}
  >
    {children}
  </div>
)
