import React, { type ReactElement } from "react";
import MUIAlert from "@mui/material/Alert";
import { Button } from "@mui/material";

import { Typography } from "../typography/Typography";
import type { IconProps } from "../icon/Icon";
import { Icon } from "../icon/Icon";

export function useToastStyles() {
  const classes = {
    root: "p-16 shadow-S300 rounded-12 w-[400px] box-border bg-N0 text-N700",
    message: "py-4 flex flex-col gap-4 flex-1",
    icon: "p-0 opacity-100",
    action: "items-start ml-12 mr-0 p-0 bg-none",
  };

  return classes;
}

export function useActionButtonStyles() {
  const classes = {
    root: "p-4 rounded-6 min-w-[unset] text-[inherit] hover:bg-N20A",
    label: "p-0",
  };

  return classes;
}

export type ToastProps = {
  severity: "success" | "warning" | "error";
  title: string;
  children?: React.ReactNode;
  description?: string;
  onClose?: () => void;
};

export function Toast({
  children,
  description,
  onClose,
  severity,
  title,
}: ToastProps) {
  const toastClasses = useToastStyles();
  const actionButtonClasses = useActionButtonStyles();

  let icon: ReactElement<IconProps>;
  const commonIconProps: Partial<IconProps> = {
    size: "28",
    weight: "bold",
  };
  switch (severity) {
    case "success":
      icon = (
        <Icon {...commonIconProps} name="checkmark-circle" color="success" />
      );
      break;
    case "warning":
      icon = (
        <Icon
          {...commonIconProps}
          name="exclamation-mark-triangle"
          color="warning"
        />
      );
      break;
    case "error":
      icon = (
        <Icon
          {...commonIconProps}
          name="exclamation-mark-octagon"
          color="danger"
        />
      );
      break;
  }

  return (
    <MUIAlert
      classes={toastClasses}
      icon={icon}
      variant="filled"
      color="info"
      onClose={onClose ?? (() => {})}
      action={
        <Button classes={actionButtonClasses}>
          <Icon name="xmark" weight="semibold" size="20" />
        </Button>
      }
    >
      <Typography weight="medium" color="inherit">
        {title}
      </Typography>
      {description && <Typography color="inherit">{description}</Typography>}
      {children}
    </MUIAlert>
  );
}
