import { ExternalToast, toast as sonnerToast, Toaster } from "sonner"

import {
  CheckCircleIcon,
  CloseLargeIcon,
  CrossCircle,
  InfoCircleIcon,
  WarningTriangle,
} from "@/components/Icons"

import Button from "../Button"
import Body from "../Text/Body"
import { ToastsProps } from "./toasts"
import { toastVariants } from "./variants"

import styles from "./toasts.module.css"

export function ToastHandler() {
  return <Toaster position="bottom-right" />
}

function getIcon(variant: ToastsProps["variant"]) {
  switch (variant) {
    case "error":
      return CrossCircle
    case "info":
      return InfoCircleIcon
    case "success":
      return CheckCircleIcon
    case "warning":
      return WarningTriangle
  }
}

export function Toast({ message, onClose, variant }: ToastsProps) {
  const className = toastVariants({ variant })
  const Icon = getIcon(variant)
  return (
    <div className={className}>
      <div className={styles.iconContainer}>
        {Icon && <Icon color="white" height={24} width={24} />}
      </div>
      <Body className={styles.message}>{message}</Body>
      <Button onClick={onClose} variant="icon" intent="text">
        <CloseLargeIcon />
      </Button>
    </div>
  )
}

export const toast = {
  success: (message: React.ReactNode, options?: ExternalToast) =>
    sonnerToast.custom(
      (t) => (
        <Toast
          variant="success"
          message={message}
          onClose={() => sonnerToast.dismiss(t)}
        />
      ),
      options
    ),
  info: (message: React.ReactNode, options?: ExternalToast) =>
    sonnerToast.custom(
      (t) => (
        <Toast
          variant="info"
          message={message}
          onClose={() => sonnerToast.dismiss(t)}
        />
      ),
      options
    ),
  error: (message: React.ReactNode, options?: ExternalToast) =>
    sonnerToast.custom(
      (t) => (
        <Toast
          variant="error"
          message={message}
          onClose={() => sonnerToast.dismiss(t)}
        />
      ),
      options
    ),
  warning: (message: React.ReactNode, options?: ExternalToast) =>
    sonnerToast.custom(
      (t) => (
        <Toast
          variant="warning"
          message={message}
          onClose={() => sonnerToast.dismiss(t)}
        />
      ),
      options
    ),
}
