import React, { useCallback } from 'react';
import { clsx } from 'clsx';
import * as BaseToast from '@radix-ui/react-toast';

import { forwardRef } from '../utils/react';
import { Alert, type AlertProps } from '../alert';
import { Box } from '../box';
import { CloseIcon } from '../icons';
import * as css from './toast.css';

export interface ToastProps
  extends Omit<BaseToast.ToastProps, 'asChild'>,
    css.ToastVariants,
    AlertProps {
  closable?: boolean;
  closeAltText?: string;
}

export type ToastStatus = AlertProps['status'];

export const Toast = forwardRef<'li', ToastProps>(function Toast(
  {
    as = 'li',
    horizontal,
    vertical,
    children,
    className,
    closable,
    closeAltText = 'Close',
    size,
    status,
    ...rest
  },
  ref,
) {
  const containerClass = clsx(
    className,
    css.toast({ size, horizontal, vertical }),
  );

  const renderCloseIcon = useCallback(
    () => (
      <BaseToast.Close className={css.closeButton} title={closeAltText}>
        <CloseIcon size="md" />
      </BaseToast.Close>
    ),
    [closeAltText],
  );

  return (
    <BaseToast.Root {...rest} asChild>
      <Box ref={ref} as={as} className={containerClass}>
        <BaseToast.Description asChild>
          <Alert
            className={css.content}
            status={status}
            action={closable && renderCloseIcon()}
          >
            {children}
          </Alert>
        </BaseToast.Description>
      </Box>
    </BaseToast.Root>
  );
});
