'use client';

import * as React from 'react';
import { motion, AnimatePresence } from 'motion/react';
import { XIcon, CheckIcon, AlertTriangleIcon, InfoIcon } from 'lucide-react';

import { cn } from '@workspace/ui/lib/utils';

// Define types for toast variants
type ToastVariant = 'default' | 'success' | 'warning' | 'error' | 'info';

interface ToastProps extends React.HTMLAttributes<HTMLDivElement> {
  variant?: ToastVariant;
  title?: string;
  description?: string;
  onOpenChange?: (open: boolean) => void;
  open?: boolean;
}

export function Toast({
  className,
  variant = 'default',
  title,
  description,
  onOpenChange,
  open,
  ...props
}: ToastProps) {
  // Define styles based on variant
  const variantStyles = {
    default: 'bg-background border',
    success: 'bg-green-500/10 border-green-500/30 text-green-500 dark:border-green-500/50 dark:bg-green-500/20 dark:text-green-300',
    warning: 'bg-yellow-500/10 border-yellow-500/30 text-yellow-500 dark:border-yellow-500/50 dark:bg-yellow-500/20 dark:text-yellow-300',
    error: 'bg-red-500/10 border-red-500/30 text-red-500 dark:border-red-500/50 dark:bg-red-500/20 dark:text-red-300',
    info: 'bg-blue-500/10 border-blue-500/30 text-blue-500 dark:border-blue-500/50 dark:bg-blue-500/20 dark:text-blue-300',
  };

  const iconMap = {
    success: <CheckIcon className="size-4" />,
    warning: <AlertTriangleIcon className="size-4" />,
    error: <XIcon className="size-4" />,
    info: <InfoIcon className="size-4" />,
    default: null,
  };

  const icon = iconMap[variant] || null;

  return (
    <AnimatePresence>
      {open && (
        <motion.div
          initial={{ opacity: 0, y: 20, scale: 0.95 }}
          animate={{ opacity: 1, y: 0, scale: 1 }}
          exit={{ opacity: 0, y: 20, scale: 0.95 }}
          transition={{ duration: 0.2 }}
          className={cn(
            "fixed top-4 right-4 z-[100] w-full max-w-sm rounded-lg border p-4 shadow-lg",
            variantStyles[variant],
            className
          )}
          {...props}
        >
          <div className="flex items-start gap-3">
            {icon && (
              <div className="flex h-5 w-5 items-center justify-center">
                {icon}
              </div>
            )}
            <div className="flex-1 space-y-1">
              {title && <div className="text-sm font-semibold">{title}</div>}
              {description && <div className="text-sm opacity-90">{description}</div>}
            </div>
            <button
              onClick={() => onOpenChange && onOpenChange(false)}
              className="opacity-70 transition-opacity hover:opacity-100"
            >
              <XIcon className="size-4" />
              <span className="sr-only">Close</span>
            </button>
          </div>
        </motion.div>
      )}
    </AnimatePresence>
  );
}