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

import {
  MaterialIcon,
  type MaterialIconSetIconProps,
} from "@scandic-hotels/design-system/Icons/MaterialIcon"

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

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

import type { ToastsProps } from "./toasts"

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

interface AlertIconProps {
  variant: ToastsProps["variant"]
}
function AlertIcon({
  variant,
  ...props
}: AlertIconProps & MaterialIconSetIconProps) {
  switch (variant) {
    case "error":
      return <MaterialIcon icon="cancel" {...props} />
    case "info":
      return <MaterialIcon icon="info" {...props} />
    case "success":
      return <MaterialIcon icon="check_circle" {...props} />
    case "warning":
      return <MaterialIcon icon="warning" {...props} />
  }
}

export function Toast({ children, message, onClose, variant }: ToastsProps) {
  const className = toastVariants({ variant })
  const Icon = <AlertIcon variant={variant} color="Icon/Inverted" />
  return (
    <div className={className}>
      <div className={styles.iconContainer}>{Icon && Icon}</div>
      {message ? (
        <Body className={styles.message}>{message}</Body>
      ) : (
        <div className={styles.content}>{children}</div>
      )}
      {onClose ? (
        <Button onClick={onClose} variant="icon" intent="tertiary">
          <MaterialIcon icon="close" />
        </Button>
      ) : null}
    </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
    ),
}
