/**
 * NotificationItem Component
 * Displays a single notification with icon, title, message, and time
 */

import { useNavigate } from 'react-router-dom';
import {
  AlertTriangle,
  TrendingUp,
  Wallet,
  CreditCard,
  DollarSign,
  Bell,
  Shield,
  User,
  Check,
  X,
} from 'lucide-react';
import clsx from 'clsx';
import type { Notification, NotificationType, NotificationIconType } from '../../../services/notification.service';

interface NotificationItemProps {
  notification: Notification;
  onMarkAsRead?: (id: string) => void;
  onDelete?: (id: string) => void;
  compact?: boolean;
}

// Icon mapping by type
const typeIcons: Record<NotificationType, React.ElementType> = {
  alert_triggered: AlertTriangle,
  trade_executed: TrendingUp,
  deposit_confirmed: Wallet,
  withdrawal_completed: CreditCard,
  distribution_received: DollarSign,
  system_announcement: Bell,
  security_alert: Shield,
  account_update: User,
};

// Color mapping by icon type
const iconColors: Record<NotificationIconType, string> = {
  success: 'text-green-400 bg-green-400/10',
  warning: 'text-yellow-400 bg-yellow-400/10',
  error: 'text-red-400 bg-red-400/10',
  info: 'text-blue-400 bg-blue-400/10',
};

// Format relative time
function formatRelativeTime(dateString: string): string {
  const date = new Date(dateString);
  const now = new Date();
  const diffMs = now.getTime() - date.getTime();
  const diffSec = Math.floor(diffMs / 1000);
  const diffMin = Math.floor(diffSec / 60);
  const diffHour = Math.floor(diffMin / 60);
  const diffDay = Math.floor(diffHour / 24);

  if (diffSec < 60) return 'Ahora';
  if (diffMin < 60) return `${diffMin}m`;
  if (diffHour < 24) return `${diffHour}h`;
  if (diffDay < 7) return `${diffDay}d`;
  return date.toLocaleDateString();
}

export default function NotificationItem({
  notification,
  onMarkAsRead,
  onDelete,
  compact = false,
}: NotificationItemProps) {
  const navigate = useNavigate();
  const Icon = typeIcons[notification.type] || Bell;
  const iconColorClass = iconColors[notification.iconType] || iconColors.info;

  const handleClick = () => {
    if (!notification.isRead && onMarkAsRead) {
      onMarkAsRead(notification.id);
    }
    if (notification.actionUrl) {
      navigate(notification.actionUrl);
    }
  };

  const handleMarkAsRead = (e: React.MouseEvent) => {
    e.stopPropagation();
    if (onMarkAsRead) {
      onMarkAsRead(notification.id);
    }
  };

  const handleDelete = (e: React.MouseEvent) => {
    e.stopPropagation();
    if (onDelete) {
      onDelete(notification.id);
    }
  };

  return (
    <div
      className={clsx(
        'flex items-start gap-3 p-3 rounded-lg cursor-pointer transition-colors group',
        notification.isRead
          ? 'bg-gray-800/50 hover:bg-gray-800'
          : 'bg-gray-800 hover:bg-gray-700',
        compact && 'p-2'
      )}
      onClick={handleClick}
    >
      {/* Icon */}
      <div
        className={clsx(
          'flex-shrink-0 p-2 rounded-lg',
          iconColorClass,
          compact && 'p-1.5'
        )}
      >
        <Icon className={clsx('w-5 h-5', compact && 'w-4 h-4')} />
      </div>

      {/* Content */}
      <div className="flex-1 min-w-0">
        <div className="flex items-start justify-between gap-2">
          <p
            className={clsx(
              'font-medium text-white truncate',
              compact ? 'text-sm' : 'text-base',
              notification.isRead && 'text-gray-300'
            )}
          >
            {notification.title}
          </p>
          <span className="text-xs text-gray-500 whitespace-nowrap">
            {formatRelativeTime(notification.createdAt)}
          </span>
        </div>
        <p
          className={clsx(
            'text-gray-400 mt-0.5',
            compact ? 'text-xs line-clamp-1' : 'text-sm line-clamp-2'
          )}
        >
          {notification.message}
        </p>

        {/* Priority badge for high/urgent */}
        {(notification.priority === 'high' || notification.priority === 'urgent') && (
          <span
            className={clsx(
              'inline-flex items-center px-1.5 py-0.5 mt-1 text-xs font-medium rounded',
              notification.priority === 'urgent'
                ? 'bg-red-500/20 text-red-400'
                : 'bg-yellow-500/20 text-yellow-400'
            )}
          >
            {notification.priority === 'urgent' ? 'Urgente' : 'Importante'}
          </span>
        )}
      </div>

      {/* Actions */}
      <div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
        {!notification.isRead && onMarkAsRead && (
          <button
            onClick={handleMarkAsRead}
            className="p-1 rounded hover:bg-gray-600 text-gray-400 hover:text-white"
            title="Marcar como leída"
          >
            <Check className="w-4 h-4" />
          </button>
        )}
        {onDelete && (
          <button
            onClick={handleDelete}
            className="p-1 rounded hover:bg-gray-600 text-gray-400 hover:text-red-400"
            title="Eliminar"
          >
            <X className="w-4 h-4" />
          </button>
        )}
      </div>

      {/* Unread indicator */}
      {!notification.isRead && (
        <div className="absolute top-3 right-3 w-2 h-2 bg-primary-500 rounded-full" />
      )}
    </div>
  );
}
