import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Badge } from '@/components/ui/badge';
import { 
  CheckCircle, 
  AlertTriangle, 
  MessageSquare, 
  Flame, 
  FileText, 
  Paperclip, 
  Activity,
  ArrowRight
} from 'lucide-react';
import { differenceInMinutes, differenceInHours, differenceInDays } from 'date-fns';

export interface ActivityData {
  activityId: string;
  requestNumber: string;
  requestTitle: string;
  action: string;
  userId: string;
  userName: string;
  timestamp: string;
  priority: string;
}

interface ActivityFeedItemProps {
  activity: ActivityData;
  currentUserId?: string;
  currentUserDisplayName?: string;
  currentUserEmail?: string;
  onNavigate?: (requestNumber: string) => void;
  testId?: string;
}

// Utility functions
const getPriorityColor = (priority: string) => {
  const p = priority.toLowerCase();
  switch (p) {
    case 'express': return 'bg-orange-100 text-orange-800 border-orange-200';
    case 'standard': return 'bg-blue-100 text-blue-800 border-blue-200';
    case 'high': return 'bg-red-100 text-red-800 border-red-200';
    case 'medium': return 'bg-orange-100 text-orange-800 border-orange-200';
    case 'low': return 'bg-green-100 text-green-800 border-green-200';
    default: return 'bg-gray-100 text-gray-800 border-gray-200';
  }
};

const getRelativeTime = (timestamp: string) => {
  const now = new Date();
  const time = new Date(timestamp);
  const diffMin = differenceInMinutes(now, time);
  
  if (diffMin < 1) return 'just now';
  if (diffMin < 60) return `${diffMin} minute${diffMin > 1 ? 's' : ''} ago`;
  
  const diffHrs = differenceInHours(now, time);
  if (diffHrs < 24) return `${diffHrs} hour${diffHrs > 1 ? 's' : ''} ago`;
  
  const diffDay = differenceInDays(now, time);
  return `${diffDay} day${diffDay > 1 ? 's' : ''} ago`;
};

const cleanActivityDescription = (desc: string) => {
  if (!desc) return desc;
  
  // Remove email addresses in parentheses
  let cleaned = desc.replace(/\s*\([^)]*@[^)]*\)/g, '');
  
  // Remove "by [user]" at the end - we show user separately
  cleaned = cleaned.replace(/\s+by\s+.+$/i, '');
  
  // Shorten common phrases
  cleaned = cleaned.replace(/has been added as approver/gi, 'added as approver');
  cleaned = cleaned.replace(/has been added as spectator/gi, 'added as spectator');
  cleaned = cleaned.replace(/has been/gi, '');
  
  // Make TAT format more compact
  cleaned = cleaned.replace(/with TAT of (\d+) hours?/gi, '(TAT: $1h)');
  cleaned = cleaned.replace(/with TAT of (\d+) days?/gi, '(TAT: $1d)');
  
  // Replace multiple spaces with single space
  cleaned = cleaned.replace(/\s+/g, ' ');
  
  return cleaned.trim();
};

const getActionIcon = (action: string) => {
  const actionLower = action.toLowerCase();
  if (actionLower.includes('approv')) return <CheckCircle className="w-2.5 h-2.5 sm:w-3 sm:h-3 text-green-600" />;
  if (actionLower.includes('reject')) return <AlertTriangle className="w-2.5 h-2.5 sm:w-3 sm:h-3 text-red-600" />;
  if (actionLower.includes('comment')) return <MessageSquare className="w-2.5 h-2.5 sm:w-3 sm:h-3 text-blue-600" />;
  if (actionLower.includes('escalat')) return <Flame className="w-2.5 h-2.5 sm:w-3 sm:h-3 text-orange-600" />;
  if (actionLower.includes('submit')) return <FileText className="w-2.5 h-2.5 sm:w-3 sm:h-3 text-purple-600" />;
  if (actionLower.includes('document')) return <Paperclip className="w-2.5 h-2.5 sm:w-3 sm:h-3 text-indigo-600" />;
  return <Activity className="w-2.5 h-2.5 sm:w-3 sm:h-3 text-gray-600" />;
};

export function ActivityFeedItem({ 
  activity, 
  currentUserId,
  currentUserDisplayName,
  currentUserEmail,
  onNavigate,
  testId = 'activity-feed-item'
}: ActivityFeedItemProps) {
  const isCurrentUser = activity.userId === currentUserId;
  const displayName = isCurrentUser ? 'You' : (activity.userName || 'System');
  
  const userInitials = isCurrentUser
    ? ((currentUserDisplayName || currentUserEmail || 'ME')
        .split(' ')
        .map((n: string) => n[0])
        .join('')
        .toUpperCase()
        .substring(0, 2))
    : activity.userName
      ? activity.userName
          .split(' ')
          .map(n => n[0])
          .join('')
          .toUpperCase()
          .substring(0, 2)
      : 'SY'; // System default

  return (
    <div 
      className="flex items-start gap-2 sm:gap-3 p-3 sm:p-4 rounded-lg hover:bg-gray-50 transition-all duration-200 cursor-pointer border border-gray-100 hover:border-gray-300"
      onClick={() => onNavigate?.(activity.requestNumber)}
      data-testid={`${testId}-${activity.activityId}`}
    >
      <div className="relative flex-shrink-0 mt-0.5">
        <Avatar 
          className={`h-8 w-8 sm:h-10 sm:w-10 ring-2 shadow-sm ${isCurrentUser ? 'ring-blue-200' : 'ring-white'}`}
          data-testid={`${testId}-avatar`}
        >
          <AvatarImage src="" />
          <AvatarFallback className={`text-white font-semibold text-xs sm:text-sm ${isCurrentUser ? 'bg-blue-600' : 'bg-slate-700'}`}>
            {userInitials}
          </AvatarFallback>
        </Avatar>
        <div className="absolute -bottom-0.5 -right-0.5 sm:-bottom-1 sm:-right-1 w-4 h-4 sm:w-5 sm:h-5 bg-white rounded-full flex items-center justify-center shadow-sm border border-gray-200">
          {getActionIcon(activity.action)}
        </div>
      </div>
      
      <div className="flex-1 min-w-0">
        {/* Header with Request Number and Priority Badge */}
        <div className="flex items-center justify-between gap-2 mb-1">
          <div className="flex items-center gap-2">
            <span 
              className="font-semibold text-xs sm:text-sm text-gray-900"
              data-testid={`${testId}-request-number`}
            >
              {activity.requestNumber}
            </span>
            <Badge 
              variant="outline" 
              className={`text-xs ${getPriorityColor(activity.priority)} font-medium flex-shrink-0`}
              data-testid={`${testId}-priority`}
            >
              {activity.priority}
            </Badge>
          </div>
        </div>

        {/* Action Description as Text */}
        <p className="text-xs text-muted-foreground mb-1 line-clamp-2">
          <span 
            className={`font-medium ${
              activity.action.toLowerCase().includes('approv') ? 'text-green-600' :
              activity.action.toLowerCase().includes('reject') ? 'text-red-600' :
              activity.action.toLowerCase().includes('submit') ? 'text-blue-600' :
              activity.action.toLowerCase().includes('add') ? 'text-indigo-600' :
              'text-gray-700'
            }`}
            data-testid={`${testId}-action`}
          >
            {cleanActivityDescription(activity.action)}
          </span>
        </p>

        {/* Request Title */}
        <p 
          className="text-xs sm:text-sm text-gray-700 line-clamp-1 mb-1"
          data-testid={`${testId}-request-title`}
        >
          {activity.requestTitle}
        </p>

        {/* User and Time */}
        <div className="flex items-center gap-1.5 text-xs text-muted-foreground">
          <span 
            className={`font-medium truncate max-w-[150px] sm:max-w-[200px] ${isCurrentUser ? 'text-blue-600' : 'text-gray-900'}`}
            data-testid={`${testId}-user-name`}
          >
            {displayName}
          </span>
          <span>•</span>
          <span 
            className="whitespace-nowrap"
            data-testid={`${testId}-timestamp`}
          >
            {getRelativeTime(activity.timestamp)}
          </span>
        </div>
      </div>
      
      <ArrowRight 
        className="h-4 w-4 text-gray-400 hover:text-blue-600 transition-colors flex-shrink-0 hidden sm:block mt-1"
        data-testid={`${testId}-arrow`}
      />
    </div>
  );
}

