import React, { useMemo, useState, useCallback } from 'react';
import { clsx } from 'clsx';
import { Avatar, Badge, Button } from '../../ui';

export interface ActivityUser {
  id: string;
  name: string;
  avatar?: string;
  role?: string;
}

export interface ActivityItem {
  id: string;
  type: ActivityType;
  title: string;
  description: string;
  timestamp: string;
  user?: ActivityUser;
  metadata?: Record<string, any>;
  status?: ActivityStatus;
  category?: string;
  
  // Navigation support
  href?: string;
  onClick?: () => void;
  
  // Visual styling
  icon?: React.ReactNode;
  color?: string;
  priority?: ActivityPriority;
}

export enum ActivityType {
  ORDER = 'order',
  PRODUCTION = 'production',
  INVENTORY = 'inventory',
  SALES = 'sales',
  USER = 'user',
  SYSTEM = 'system',
  QUALITY = 'quality',
  SUPPLIER = 'supplier',
  FINANCE = 'finance',
  ALERT = 'alert'
}

export enum ActivityStatus {
  SUCCESS = 'success',
  WARNING = 'warning',
  ERROR = 'error',
  INFO = 'info',
  PENDING = 'pending',
  IN_PROGRESS = 'in_progress',
  CANCELLED = 'cancelled'
}

export enum ActivityPriority {
  LOW = 'low',
  MEDIUM = 'medium',
  HIGH = 'high',
  URGENT = 'urgent'
}

export interface RecentActivityProps {
  activities: ActivityItem[];
  
  // Display configuration
  maxItems?: number;
  showTimestamp?: boolean;
  showUserAvatar?: boolean;
  showTypeIcons?: boolean;
  compact?: boolean;
  
  // Filtering
  allowFiltering?: boolean;
  filterTypes?: ActivityType[];
  defaultFilter?: ActivityType | 'all';
  
  // Pagination and loading
  hasMore?: boolean;
  isLoading?: boolean;
  onLoadMore?: () => void;
  
  // Event handlers
  onActivityClick?: (activity: ActivityItem) => void;
  onRefresh?: () => void;
  
  // Accessibility and styling
  className?: string;
  'aria-label'?: string;
  emptyMessage?: string;
}

// Spanish activity type labels and icons
const ACTIVITY_CONFIG = {
  [ActivityType.ORDER]: {
    label: 'Pedidos',
    icon: (
      <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5H7a2 2 0 00-2 2v10a2 2 0 002 2h8a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
      </svg>
    ),
    color: 'blue',
    bgColor: 'bg-[var(--color-info)]/10',
    textColor: 'text-[var(--color-info)]',
    borderColor: 'border-[var(--color-info)]/20'
  },
  [ActivityType.PRODUCTION]: {
    label: 'Producción',
    icon: (
      <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
      </svg>
    ),
    color: 'orange',
    bgColor: 'bg-[var(--color-primary)]/10',
    textColor: 'text-[var(--color-primary)]',
    borderColor: 'border-orange-200'
  },
  [ActivityType.INVENTORY]: {
    label: 'Inventario',
    icon: (
      <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4" />
      </svg>
    ),
    color: 'purple',
    bgColor: 'bg-purple-100',
    textColor: 'text-purple-600',
    borderColor: 'border-purple-200'
  },
  [ActivityType.SALES]: {
    label: 'Ventas',
    icon: (
      <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
      </svg>
    ),
    color: 'green',
    bgColor: 'bg-[var(--color-success)]/10',
    textColor: 'text-[var(--color-success)]',
    borderColor: 'border-green-200'
  },
  [ActivityType.USER]: {
    label: 'Usuarios',
    icon: (
      <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
      </svg>
    ),
    color: 'indigo',
    bgColor: 'bg-indigo-100',
    textColor: 'text-indigo-600',
    borderColor: 'border-indigo-200'
  },
  [ActivityType.SYSTEM]: {
    label: 'Sistema',
    icon: (
      <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
      </svg>
    ),
    color: 'gray',
    bgColor: 'bg-[var(--bg-tertiary)]',
    textColor: 'text-[var(--text-secondary)]',
    borderColor: 'border-[var(--border-primary)]'
  },
  [ActivityType.QUALITY]: {
    label: 'Calidad',
    icon: (
      <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
      </svg>
    ),
    color: 'green',
    bgColor: 'bg-[var(--color-success)]/10',
    textColor: 'text-[var(--color-success)]',
    borderColor: 'border-green-200'
  },
  [ActivityType.SUPPLIER]: {
    label: 'Proveedores',
    icon: (
      <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z" />
      </svg>
    ),
    color: 'teal',
    bgColor: 'bg-teal-100',
    textColor: 'text-teal-600',
    borderColor: 'border-teal-200'
  },
  [ActivityType.FINANCE]: {
    label: 'Finanzas',
    icon: (
      <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
      </svg>
    ),
    color: 'emerald',
    bgColor: 'bg-emerald-100',
    textColor: 'text-emerald-600',
    borderColor: 'border-emerald-200'
  },
  [ActivityType.ALERT]: {
    label: 'Alertas',
    icon: (
      <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.732-.833-2.464 0L4.35 16.5c-.77.833.192 2.5 1.732 2.5z" />
      </svg>
    ),
    color: 'red',
    bgColor: 'bg-[var(--color-error)]/10',
    textColor: 'text-[var(--color-error)]',
    borderColor: 'border-red-200'
  }
};

const STATUS_CONFIG = {
  [ActivityStatus.SUCCESS]: { color: 'green', bgColor: 'bg-green-500' },
  [ActivityStatus.WARNING]: { color: 'yellow', bgColor: 'bg-yellow-500' },
  [ActivityStatus.ERROR]: { color: 'red', bgColor: 'bg-red-500' },
  [ActivityStatus.INFO]: { color: 'blue', bgColor: 'bg-[var(--color-info)]/50' },
  [ActivityStatus.PENDING]: { color: 'gray', bgColor: 'bg-[var(--bg-secondary)]0' },
  [ActivityStatus.IN_PROGRESS]: { color: 'purple', bgColor: 'bg-purple-500' },
  [ActivityStatus.CANCELLED]: { color: 'gray', bgColor: 'bg-gray-400' }
};

const formatRelativeTime = (timestamp: string): string => {
  const date = new Date(timestamp);
  const now = new Date();
  const diffInMs = now.getTime() - date.getTime();
  const diffInMinutes = Math.floor(diffInMs / (1000 * 60));
  const diffInHours = Math.floor(diffInMinutes / 60);
  const diffInDays = Math.floor(diffInHours / 24);

  if (diffInMinutes < 1) {
    return 'Ahora mismo';
  } else if (diffInMinutes < 60) {
    return `Hace ${diffInMinutes} min`;
  } else if (diffInHours < 24) {
    return `Hace ${diffInHours}h`;
  } else if (diffInDays === 1) {
    return 'Ayer';
  } else if (diffInDays < 7) {
    return `Hace ${diffInDays} días`;
  } else {
    return date.toLocaleDateString('es-ES', {
      day: 'numeric',
      month: 'short'
    });
  }
};

const RecentActivity: React.FC<RecentActivityProps> = ({
  activities,
  maxItems = 10,
  showTimestamp = true,
  showUserAvatar = true,
  showTypeIcons = true,
  compact = false,
  allowFiltering = true,
  filterTypes = Object.values(ActivityType),
  defaultFilter = 'all',
  hasMore = false,
  isLoading = false,
  onLoadMore,
  onActivityClick,
  onRefresh,
  className,
  'aria-label': ariaLabel = 'Actividad reciente',
  emptyMessage = 'No hay actividad reciente'
}) => {
  const [activeFilter, setActiveFilter] = useState<ActivityType | 'all'>(defaultFilter);

  const filteredActivities = useMemo(() => {
    let filtered = activities;
    
    if (activeFilter !== 'all') {
      filtered = activities.filter(activity => activity.type === activeFilter);
    }
    
    return filtered.slice(0, maxItems);
  }, [activities, activeFilter, maxItems]);

  const handleActivityClick = useCallback((activity: ActivityItem) => {
    onActivityClick?.(activity);
    if (activity.onClick) {
      activity.onClick();
    }
  }, [onActivityClick]);

  const renderActivityItem = (activity: ActivityItem) => {
    const config = ACTIVITY_CONFIG[activity.type] || {
      label: 'Actividad',
      icon: <div className="w-4 h-4 bg-gray-300 rounded" />,
      color: 'gray',
      bgColor: 'bg-[var(--bg-tertiary)]',
      textColor: 'text-[var(--text-secondary)]',
      borderColor: 'border-[var(--border-primary)]'
    };
    const statusConfig = activity.status ? STATUS_CONFIG[activity.status] : null;
    
    const itemClasses = clsx(
      'group relative flex items-start gap-3 p-3 rounded-lg transition-all duration-200',
      'hover:bg-[var(--bg-secondary)] hover:shadow-sm',
      {
        'cursor-pointer': activity.onClick || activity.href,
        'p-2': compact,
        'border-l-4': !compact,
        [config.borderColor]: !compact
      }
    );

    return (
      <div
        key={activity.id}
        className={itemClasses}
        onClick={activity.onClick || activity.href ? () => handleActivityClick(activity) : undefined}
        role={activity.onClick || activity.href ? 'button' : undefined}
        tabIndex={activity.onClick || activity.href ? 0 : undefined}
      >
        {/* Timeline indicator */}
        <div className="relative flex-shrink-0">
          {showTypeIcons && (
            <div className={clsx(
              'flex items-center justify-center rounded-full',
              {
                'w-8 h-8': !compact,
                'w-6 h-6': compact
              },
              config.bgColor,
              config.textColor
            )}>
              {activity.icon || config.icon}
            </div>
          )}
          
          {/* Status indicator */}
          {activity.status && statusConfig && (
            <div className={clsx(
              'absolute -bottom-1 -right-1 w-3 h-3 rounded-full border-2 border-white',
              statusConfig.bgColor
            )} />
          )}
        </div>

        {/* Content */}
        <div className="flex-1 min-w-0">
          <div className="flex items-start justify-between gap-2">
            <div className="min-w-0 flex-1">
              <p className={clsx(
                'font-medium text-[var(--text-primary)] truncate',
                {
                  'text-sm': compact,
                  'text-base': !compact
                }
              )}>
                {activity.title}
              </p>
              <p className={clsx(
                'text-[var(--text-secondary)] mt-1',
                {
                  'text-xs line-clamp-1': compact,
                  'text-sm line-clamp-2': !compact
                }
              )}>
                {activity.description}
              </p>
              
              {/* User info */}
              {activity.user && showUserAvatar && (
                <div className="flex items-center gap-2 mt-2">
                  <Avatar
                    size="xs"
                    src={activity.user.avatar}
                    alt={activity.user.name}
                  />
                  <span className="text-xs text-[var(--text-tertiary)]">
                    {activity.user.name}
                  </span>
                </div>
              )}
            </div>
            
            {/* Timestamp */}
            {showTimestamp && (
              <time className={clsx(
                'text-[var(--text-tertiary)] flex-shrink-0',
                {
                  'text-xs': compact,
                  'text-sm': !compact
                }
              )}>
                {formatRelativeTime(activity.timestamp)}
              </time>
            )}
          </div>
        </div>
      </div>
    );
  };

  if (activities.length === 0) {
    return (
      <div className="text-center py-8 text-[var(--text-tertiary)]">
        <div className="text-[var(--text-tertiary)] mb-4">
          <svg
            className="w-12 h-12 mx-auto"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M9 5H7a2 2 0 00-2 2v10a2 2 0 002 2h8a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"
            />
          </svg>
        </div>
        <p>{emptyMessage}</p>
      </div>
    );
  }

  return (
    <div className={clsx('space-y-4', className)} aria-label={ariaLabel}>
      {/* Filters */}
      {allowFiltering && filterTypes.length > 1 && (
        <div className="flex items-center gap-2 pb-2 border-b border-[var(--border-primary)]">
          <Button
            variant={activeFilter === 'all' ? 'primary' : 'ghost'}
            size="sm"
            onClick={() => setActiveFilter('all')}
          >
            Todos
          </Button>
          {filterTypes.map((type) => {
            const config = ACTIVITY_CONFIG[type] || {
              label: 'Actividad',
              icon: <div className="w-4 h-4 bg-gray-300 rounded" />,
              color: 'gray',
              bgColor: 'bg-[var(--bg-tertiary)]',
              textColor: 'text-[var(--text-secondary)]',
              borderColor: 'border-[var(--border-primary)]'
            };
            const count = activities.filter(a => a.type === type).length;
            
            return (
              <Button
                key={type}
                variant={activeFilter === type ? 'primary' : 'ghost'}
                size="sm"
                onClick={() => setActiveFilter(type)}
                leftIcon={config.icon}
              >
                {config.label}
                {count > 0 && (
                  <Badge size="xs" className="ml-1">
                    {count}
                  </Badge>
                )}
              </Button>
            );
          })}
          
          {onRefresh && (
            <div className="ml-auto">
              <Button
                variant="ghost"
                size="sm"
                onClick={onRefresh}
                aria-label="Actualizar actividad"
              >
                <svg
                  className="w-4 h-4"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={2}
                    d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"
                  />
                </svg>
              </Button>
            </div>
          )}
        </div>
      )}

      {/* Activity list */}
      <div className="space-y-1">
        {filteredActivities.map(renderActivityItem)}
      </div>

      {/* Loading state */}
      {isLoading && (
        <div className="flex justify-center py-4">
          <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-blue-500" />
        </div>
      )}

      {/* Load more */}
      {hasMore && onLoadMore && !isLoading && (
        <div className="text-center pt-4">
          <Button
            variant="ghost"
            size="sm"
            onClick={onLoadMore}
          >
            Ver más actividad
          </Button>
        </div>
      )}
    </div>
  );
};

RecentActivity.displayName = 'RecentActivity';

export default RecentActivity;