import React from 'react';
import { Trash2, Plus, Edit } from 'lucide-react';
import { User } from '../../types';
import { useAuth } from '../../context/AuthContext';

interface ContactCardProps {
  user: User;
  onClick?: () => void;
  onEdit?: (user: User) => void;
  onDelete?: (user: User) => void;
  onCreateChild?: (user: User) => void;
  viewMode?: 'grid' | 'tree' | 'organizational';
  showActions?: boolean;
  isAdmin?: boolean;
  isSuperAdmin?: boolean;
  isChild?: boolean;
}

const ContactCard: React.FC<ContactCardProps> = ({ 
  user, 
  onClick, 
  onEdit,
  onDelete, 
  onCreateChild,
  viewMode = 'grid', 
  showActions = false,
  isAdmin = false,
  isSuperAdmin = false,
  isChild = false
}) => {
  const { user: currentUser, hasPermission } = useAuth();
  const getStatusColor = (status: User['status']) => {
    switch (status) {
      case 'online': return 'bg-green-500';
      case 'busy': return 'bg-yellow-500';
      case 'offline': return 'bg-gray-500';
      default: return 'bg-gray-500';
    }
  };

  // Adjust card size based on view mode
  const cardClasses = viewMode === 'organizational' 
    ? `bg-white rounded-lg shadow-md hover:shadow-lg transition-shadow p-2 cursor-pointer ${isChild ? 'bg-blue-50 border border-blue-200' : ''}`
    : "bg-white rounded-lg shadow-md hover:shadow-lg transition-shadow p-4 cursor-pointer";

  const avatarSize = viewMode === 'organizational' ? "w-6 h-6" : "w-10 h-10";
  const avatarTextSize = viewMode === 'organizational' ? "text-xs" : "text-sm";
  const statusDotSize = viewMode === 'organizational' ? "w-1.5 h-1.5" : "w-3 h-3";
  const spacingClass = viewMode === 'organizational' ? "space-x-2" : "space-x-3";

  const handleDelete = (e: React.MouseEvent) => {
    e.stopPropagation();
    onDelete?.(user);
  };

  const handleEdit = (e: React.MouseEvent) => {
    e.stopPropagation();
    onEdit?.(user);
  };

  const handleCreateChild = (e: React.MouseEvent) => {
    e.stopPropagation();
    onCreateChild?.(user);
  };

  // Check permissions for Role 16 (navy_admin)
  const canCreate = isAdmin || isSuperAdmin || currentUser?.role_id === 16 || hasPermission('contact.create') || hasPermission('directory.contact.create');
  const canEdit = isAdmin || isSuperAdmin || currentUser?.role_id === 16 || hasPermission('contact.update') || hasPermission('directory.contact.edit');
  const canDelete = isAdmin || isSuperAdmin || currentUser?.role_id === 16 || hasPermission('contact.delete') || hasPermission('directory.contact.delete');

  // Debug logging for Role 16
  console.log('🔍 ContactCard Debug:', {
    user: user.designation,
    currentUser: currentUser?.name,
    roleId: currentUser?.role_id,
    isAdmin,
    isSuperAdmin,
    canCreate,
    canEdit,
    canDelete,
    showActions,
    permissions: currentUser?.permissions?.slice(0, 5) // Show first 5 permissions
  });

  return (
    <div 
      className={cardClasses}
      onClick={onClick}
    >
      <div className={`flex items-center ${spacingClass}`}>
        <div className="relative">
          {user.logo ? (
            <img
              src={user.logo}
              alt={user.name}
              className={`${avatarSize} rounded-full object-cover`}
            />
          ) : (
            <div className={`${avatarSize} bg-blue-600 rounded-full flex items-center justify-center text-white font-semibold ${avatarTextSize}`}>
              {user.designation.split(' ').map(n => n[0]).join('').slice(0, 2)}
            </div>
          )}
          <div className={`absolute -bottom-0.5 -right-0.5 ${statusDotSize} ${getStatusColor(user.status)} rounded-full border border-white`}></div>
        </div>
        
        <div className="flex-1 min-w-0">
          <h3 className={`font-semibold text-gray-900 ${viewMode === 'organizational' ? 'text-xs' : 'text-sm'} truncate`}>
            {user.designation}
          </h3>
          <p className={`text-gray-500 truncate ${viewMode === 'organizational' ? 'text-xs' : 'text-xs'}`}>
            {user.unit}
          </p>
          {user.time && (
            <p className={`text-gray-400 truncate ${viewMode === 'organizational' ? 'text-[10px]' : 'text-xs'}`}>
              🕒 {user.time}
            </p>
          )}
        </div>

        {showActions && (canCreate || canEdit || canDelete) && (
          <div className="flex items-center space-x-1">
            {onCreateChild && canCreate && (
              <button
                onClick={handleCreateChild}
                className="p-1 text-green-500 hover:text-green-700 hover:bg-green-50 rounded transition-colors"
                title="Create child user"
              >
                <Plus className="h-3 w-3" />
              </button>
            )}
            {onEdit && canEdit && (
              <button
                onClick={handleEdit}
                className="p-1 text-blue-500 hover:text-blue-700 hover:bg-blue-50 rounded transition-colors"
                title="Edit contact"
              >
                <Edit className="h-3 w-3" />
              </button>
            )}
            {onDelete && canDelete && (
              <button
                onClick={handleDelete}
                className="p-1 text-red-500 hover:text-red-700 hover:bg-red-50 rounded transition-colors"
                title="Delete contact"
              >
                <Trash2 className="h-3 w-3" />
              </button>
            )}
          </div>
        )}
      </div>
    </div>
  );
};

export default ContactCard;
