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 {
  Edit as EditIcon,
  Delete as DeleteIcon,
  VpnKey as KeyIcon,
} from '@mui/icons-material';
import { Permission, PermissionModule } from '../../types/permissions';

// Module color palette
const MODULE_COLORS: Record<PermissionModule, string> = {
  dashboard: '#4CAF50',
  calendar: '#2196F3',
  data: '#9C27B0',
  tasks: '#FF9800',
  bhb: '#795548',
  lorawan: '#00BCD4',
  zeiterfassung: '#E91E63',
  system: '#607D8B',
  config: '#FFC107',
};

// Module display names
const MODULE_NAMES: Record<PermissionModule, string> = {
  dashboard: 'Dashboard',
  calendar: 'Calendar',
  data: 'Data',
  tasks: 'Tasks',
  bhb: 'BHB',
  lorawan: 'LoRaWAN',
  zeiterfassung: 'Zeiterfassung',
  system: 'System',
  config: 'Config',
};

interface PermissionNodeProps {
  permission: Permission;
  isSelected?: boolean;
  isHovered?: boolean;
  isDragging?: boolean;
  showActions?: boolean;
  compact?: boolean;
  onEdit?: (permission: Permission) => void;
  onDelete?: (permission: Permission) => void;
  onClick?: (permission: Permission) => void;
}

const PermissionNode: React.FC<PermissionNodeProps> = ({
  permission,
  isSelected = false,
  isHovered = false,
  isDragging = false,
  showActions = true,
  compact = false,
  onEdit,
  onDelete,
  onClick,
}) => {
  const moduleColor = MODULE_COLORS[permission.perm_module] || '#666';
  const moduleName = MODULE_NAMES[permission.perm_module] || permission.perm_module;

  return (
    <Paper
      elevation={isDragging ? 6 : isSelected ? 3 : 1}
      sx={{
        p: compact ? 0.75 : 1.25,
        borderRadius: 1.5,
        cursor: 'pointer',
        border: '2px solid',
        borderColor: isSelected
          ? moduleColor
          : isHovered
          ? 'info.main'
          : 'transparent',
        bgcolor: permission.perm_active ? 'background.paper' : 'action.disabledBackground',
        opacity: isDragging ? 0.8 : permission.perm_active ? 1 : 0.6,
        transform: isDragging ? 'scale(1.02)' : 'scale(1)',
        transition: 'all 0.2s ease',
        minWidth: compact ? 100 : 160,
        position: 'relative',
        '&:hover': {
          borderColor: 'info.main',
          boxShadow: 2,
        },
      }}
      onClick={() => onClick?.(permission)}
    >
      {/* Module indicator bar */}
      <Box
        sx={{
          position: 'absolute',
          left: 0,
          top: 0,
          bottom: 0,
          width: 4,
          bgcolor: moduleColor,
          borderTopLeftRadius: 4,
          borderBottomLeftRadius: 4,
        }}
      />

      {/* Content */}
      <Box sx={{ pl: 1 }}>
        {/* Header with icon */}
        <Box
          sx={{
            display: 'flex',
            alignItems: 'center',
            gap: 0.5,
            mb: compact ? 0 : 0.5,
          }}
        >
          <KeyIcon
            sx={{
              fontSize: compact ? 14 : 16,
              color: moduleColor,
            }}
          />
          <Typography
            variant={compact ? 'caption' : 'body2'}
            fontWeight={600}
            sx={{
              flexGrow: 1,
              overflow: 'hidden',
              textOverflow: 'ellipsis',
              whiteSpace: 'nowrap',
            }}
          >
            {permission.perm_name}
          </Typography>
        </Box>

        {/* Permission code */}
        {!compact && (
          <Typography
            variant="caption"
            sx={{
              display: 'block',
              fontFamily: 'monospace',
              fontSize: 10,
              color: 'text.secondary',
              overflow: 'hidden',
              textOverflow: 'ellipsis',
              whiteSpace: 'nowrap',
              mb: 0.5,
            }}
          >
            {permission.perm_code}
          </Typography>
        )}

        {/* Module and category chips */}
        {!compact && (
          <Box sx={{ display: 'flex', gap: 0.5, flexWrap: 'wrap', mb: showActions ? 0.5 : 0 }}>
            <Chip
              size="small"
              label={moduleName}
              sx={{
                height: 18,
                fontSize: 9,
                bgcolor: `${moduleColor}20`,
                color: moduleColor,
                '& .MuiChip-label': { px: 0.75 },
              }}
            />
            {permission.perm_category && (
              <Chip
                size="small"
                label={permission.perm_category}
                variant="outlined"
                sx={{
                  height: 18,
                  fontSize: 9,
                  '& .MuiChip-label': { px: 0.75 },
                }}
              />
            )}
          </Box>
        )}

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

        {/* Action buttons */}
        {showActions && !compact && (
          <Box
            sx={{
              display: 'flex',
              justifyContent: 'flex-end',
              gap: 0.5,
              mt: 0.5,
            }}
            onClick={(e) => e.stopPropagation()}
          >
            <Tooltip title="Edit permission">
              <IconButton size="small" onClick={() => onEdit?.(permission)}>
                <EditIcon sx={{ fontSize: 16 }} />
              </IconButton>
            </Tooltip>

            <Tooltip title="Delete permission">
              <IconButton
                size="small"
                color="error"
                onClick={() => onDelete?.(permission)}
              >
                <DeleteIcon sx={{ fontSize: 16 }} />
              </IconButton>
            </Tooltip>
          </Box>
        )}
      </Box>

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

export default PermissionNode;
