import { HTMLAttributes, ReactNode } from 'react';
import { cn } from '../lib/cn';

export type ToastVariant = 'info' | 'success' | 'warning' | 'danger';

export interface ToastProps extends Omit<HTMLAttributes<HTMLDivElement>, 'title'> {
  variant?: ToastVariant;
  title: ReactNode;
  description?: ReactNode;
  icon?: ReactNode;
  onClose?: () => void;
}

const iconBg: Record<ToastVariant, string> = {
  info: 'bg-info-soft text-info',
  success: 'bg-success-soft text-success',
  warning: 'bg-warning-soft text-warning',
  danger: 'bg-danger-soft text-danger',
};

function DefaultIcon({ variant }: { variant: ToastVariant }) {
  if (variant === 'success') {
    return (
      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3">
        <polyline points="20 6 9 17 4 12" />
      </svg>
    );
  }
  if (variant === 'warning') {
    return (
      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3">
        <path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z" />
        <line x1="12" y1="9" x2="12" y2="13" />
        <line x1="12" y1="17" x2="12.01" y2="17" />
      </svg>
    );
  }
  if (variant === 'danger') {
    return (
      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3">
        <circle cx="12" cy="12" r="10" />
        <line x1="15" y1="9" x2="9" y2="15" />
        <line x1="9" y1="9" x2="15" y2="15" />
      </svg>
    );
  }
  return (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3">
      <line x1="12" y1="16" x2="12" y2="12" />
      <line x1="12" y1="8" x2="12.01" y2="8" />
    </svg>
  );
}

export function Toast({
  variant = 'info',
  title,
  description,
  icon,
  onClose,
  className,
  ...rest
}: ToastProps) {
  return (
    <div
      role="status"
      className={cn(
        'flex items-start gap-3 p-4 rounded-xl bg-surface border border-border shadow-md',
        className,
      )}
      {...rest}
    >
      <div
        className={cn(
          'flex items-center justify-center shrink-0 rounded-full mt-0.5 w-6 h-6',
          iconBg[variant],
        )}
      >
        {icon ?? <DefaultIcon variant={variant} />}
      </div>
      <div className="flex-1 min-w-0">
        <div className="text-sm font-medium text-text">{title}</div>
        {description && (
          <div className="text-xs mt-0.5 text-text-2">{description}</div>
        )}
      </div>
      {onClose && (
        <button
          type="button"
          onClick={onClose}
          aria-label="Close"
          className="shrink-0 text-lg leading-none mt-0.5 text-text-3 hover:text-text transition-colors"
        >
          ×
        </button>
      )}
    </div>
  );
}
