import { toast as sonnerToast } from 'sonner'
import { cn } from '../../utils/cn'
import Icon from './Icon'
import {
  ToastAction,
  ToastClose,
  ToastCountdown,
  ToastDescription,
  ToastRoot,
  ToastTitle,
} from './ToastElements'
import { type Variant } from './variants'

export type ToastProps = {
  title?: string
  description: string
  variant?: Variant
  action?: { label: string; onClick: VoidFunction }
  toastId?: string | number
  close?: boolean | undefined
  countdown?: boolean | undefined
  duration?: number | undefined
  className?: string | undefined
}

export const Toast = ({
  title,
  description,
  variant = 'info',
  action,
  toastId,
  close = true,
  countdown = true,
  className,
}: ToastProps) => (
  <div className={cn('flex w-full justify-center', className)}>
    <ToastRoot variant={variant}>
      <Icon variant={variant} />
      <div className="flex flex-1 flex-col">
        {title && <ToastTitle>{title}</ToastTitle>}
        <ToastDescription>{description}</ToastDescription>
      </div>
      {action !== undefined && (
        <ToastAction
          action={action}
          toastId={toastId}
          onClick={() => action.onClick}
        >
          {action.label}
        </ToastAction>
      )}
      {close && <ToastClose toastId={toastId} />}
      {countdown && <ToastCountdown />}
    </ToastRoot>
  </div>
)

export function toast(props: ToastProps) {
  return sonnerToast.custom(
    (toastId) => <Toast {...props} toastId={toastId} />,
    {
      position: 'top-center',
      unstyled: true,
      duration: props.duration ?? 8000,
    },
  )
}
