import React from 'react';
import Box from '@mui/material/Box';
import Paper from '@mui/material/Paper';
import Typography from '@mui/material/Typography';
import Chip from '@mui/material/Chip';
import IconButton from '@mui/material/IconButton';
import Tooltip from '@mui/material/Tooltip';
import Badge from '@mui/material/Badge';
import {
  Edit as EditIcon,
  Delete as DeleteIcon,
  Security as SecurityIcon,
  LinkOff as LinkOffIcon,
} from '@mui/icons-material';
import { SystemRole } from '../../types/permissions';

interface RoleNodeProps {
  role: SystemRole;
  isSelected?: boolean;
  isHovered?: boolean;
  isDragging?: boolean;
  showActions?: boolean;
  compact?: boolean;
  onEdit?: (role: SystemRole) => void;
  onDelete?: (role: SystemRole) => void;
  onStartConnection?: (roleId: number) => void;
  onClick?: (role: SystemRole) => void;
}

const RoleNode: React.FC<RoleNodeProps> = ({
  role,
  isSelected = false,
  isHovered = false,
  isDragging = false,
  showActions = true,
  compact = false,
  onEdit,
  onDelete,
  onStartConnection,
  onClick,
}) => {
  const permissionCount = role.permissions_count ?? role.permissions?.length ?? 0;
  const userCount = role.users_count ?? role.users?.length ?? 0;

  return (
    <Paper
      elevation={isDragging ? 8 : isSelected ? 4 : 2}
      sx={{
        p: compact ? 1 : 1.5,
        borderRadius: 2,
        cursor: 'pointer',
        border: '2px solid',
        borderColor: isSelected
          ? 'primary.main'
          : isHovered
          ? 'info.main'
          : 'transparent',
        bgcolor: role.role_active ? 'background.paper' : 'action.disabledBackground',
        opacity: isDragging ? 0.8 : role.role_active ? 1 : 0.7,
        transform: isDragging ? 'scale(1.02)' : 'scale(1)',
        transition: 'all 0.2s ease',
        minWidth: compact ? 120 : 180,
        '&:hover': {
          borderColor: 'info.main',
          boxShadow: 3,
        },
      }}
      onClick={() => onClick?.(role)}
    >
      {/* Header with color indicator */}
      <Box
        sx={{
          display: 'flex',
          alignItems: 'center',
          gap: 1,
          mb: compact ? 0 : 1,
        }}
      >
        <Box
          sx={{
            width: 12,
            height: 12,
            borderRadius: '50%',
            bgcolor: role.role_color || '#1976D2',
            flexShrink: 0,
          }}
        />
        <Typography
          variant={compact ? 'body2' : 'subtitle2'}
          fontWeight={600}
          sx={{
            flexGrow: 1,
            overflow: 'hidden',
            textOverflow: 'ellipsis',
            whiteSpace: 'nowrap',
          }}
        >
          {role.role_name}
        </Typography>

        {role.role_is_system && (
          <Tooltip title="System role (cannot be deleted)">
            <SecurityIcon fontSize="small" color="action" />
          </Tooltip>
        )}
      </Box>

      {/* Description (only in non-compact mode) */}
      {!compact && role.role_description && (
        <Typography
          variant="caption"
          color="text.secondary"
          sx={{
            display: 'block',
            mb: 1,
            overflow: 'hidden',
            textOverflow: 'ellipsis',
            whiteSpace: 'nowrap',
          }}
        >
          {role.role_description}
        </Typography>
      )}

      {/* Stats badges */}
      {!compact && (
        <Box sx={{ display: 'flex', gap: 0.5, mb: showActions ? 1 : 0 }}>
          <Chip
            size="small"
            label={`${permissionCount} permissions`}
            variant="outlined"
            sx={{ fontSize: 10 }}
          />
          <Chip
            size="small"
            label={`${userCount} users`}
            variant="outlined"
            sx={{ fontSize: 10 }}
          />
        </Box>
      )}

      {/* Action buttons */}
      {showActions && !compact && (
        <Box
          sx={{
            display: 'flex',
            justifyContent: 'flex-end',
            gap: 0.5,
            mt: 1,
          }}
          onClick={(e) => e.stopPropagation()}
        >
          <Tooltip title="Connect to permission">
            <IconButton
              size="small"
              onClick={() => onStartConnection?.(role.role_id)}
            >
              <LinkOffIcon fontSize="small" />
            </IconButton>
          </Tooltip>

          <Tooltip title="Edit role">
            <IconButton size="small" onClick={() => onEdit?.(role)}>
              <EditIcon fontSize="small" />
            </IconButton>
          </Tooltip>

          {!role.role_is_system && (
            <Tooltip title="Delete role">
              <IconButton
                size="small"
                color="error"
                onClick={() => onDelete?.(role)}
              >
                <DeleteIcon fontSize="small" />
              </IconButton>
            </Tooltip>
          )}
        </Box>
      )}

      {/* Inactive badge */}
      {!role.role_active && (
        <Chip
          size="small"
          label="Inactive"
          color="default"
          sx={{
            position: 'absolute',
            top: -8,
            right: -8,
            fontSize: 9,
          }}
        />
      )}
    </Paper>
  );
};

export default RoleNode;
