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

import {
  CheckCircleIcon,
  CloseLarge,
  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 />
}

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">
        <CloseLarge />
      </Button>
    </div>
  )
}

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