import * as React from 'react';
import { X } from 'lucide-react';

import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';

export interface ToastProps {
  title?: string;
  description?: string;
  variant?: 'default' | 'destructive' | 'success';
  onClose?: () => void;
}

const Toast = React.forwardRef<HTMLDivElement, ToastProps>(
  ({ title, description, variant = 'default', onClose, ...props }, ref) => {
    const [isVisible, setIsVisible] = React.useState(true);

    React.useEffect(() => {
      const timer = setTimeout(() => {
        setIsVisible(false);
        setTimeout(() => {
          onClose?.();
        }, 150);
      }, 3000);

      return () => clearTimeout(timer);
    }, [onClose]);

    if (!isVisible) return null;

    return (
      <div
        ref={ref}
        className={cn(
          'fixed top-4 right-4 z-50 w-full max-w-sm rounded-lg border bg-background p-4 shadow-lg',
          'animate-in slide-in-from-top-2 duration-300',
          {
            'border-red-200 bg-red-50': variant === 'destructive',
            'border-green-200 bg-green-50': variant === 'success',
          },
        )}
        {...props}
      >
        <div className="flex items-start gap-3">
          <div className="flex-1">
            {title && (
              <div
                className={cn('text-sm font-semibold', {
                  'text-red-900': variant === 'destructive',
                  'text-green-900': variant === 'success',
                  'text-foreground': variant === 'default',
                })}
              >
                {title}
              </div>
            )}
            {description && (
              <div
                className={cn('text-sm', {
                  'text-red-700': variant === 'destructive',
                  'text-green-700': variant === 'success',
                  'text-muted-foreground': variant === 'default',
                })}
              >
                {description}
              </div>
            )}
          </div>
          <Button
            variant="ghost"
            size="icon"
            className="h-6 w-6"
            onClick={() => {
              setIsVisible(false);
              setTimeout(() => onClose?.(), 150);
            }}
          >
            <X className="h-3 w-3" />
          </Button>
        </div>
      </div>
    );
  },
);
Toast.displayName = 'Toast';

export { Toast };
