import React, { useState, useEffect } from 'react';
import {
  Box,
  Container,
  Paper,
  Typography,
  Grid,
  Card,
  CardContent,
  Chip,
  Alert,
  CircularProgress,
  Tabs,
  Tab,
  Button,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  LinearProgress,
  IconButton,
  Tooltip,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  List,
  ListItem,
  ListItemText,
  ListItemIcon,
  Divider,
  TextField,
  MenuItem,
  FormControl,
  InputLabel,
  Select
} from '@mui/material';
import {
  Security,
  BugReport,
  Refresh,
  Download,
  Warning,
  CheckCircle,
  Error as ErrorIcon,
  Info,
  Shield,
  Description,
  Assessment,
  Timeline,
  Visibility,
  TrendingUp,
  Lock,
  VpnKey,
  AccountCircle,
  ArrowBack
} from '@mui/icons-material';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
import { useAuthStore } from '../store/authStore';
import { useSecurityNotification } from '../components/SecurityNotificationProvider';
import axios from 'axios';
import { format } from 'date-fns';

const TabPanel = ({ children, value, index, ...other }) => {
  return (
    <div
      role="tabpanel"
      hidden={value !== index}
      id={`security-tabpanel-${index}`}
      aria-labelledby={`security-tab-${index}`}
      {...other}
    >
      {value === index && <Box sx={{ py: 3 }}>{children}</Box>}
    </div>
  );
};

const SecurityMonitor = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const { token, user } = useAuthStore();
  const { notifySecuritySuccess, notifySecurityError } = useSecurityNotification();

  const [loading, setLoading] = useState(true);
  const [tabValue, setTabValue] = useState(0);
  const [securityStatus, setSecurityStatus] = useState(null);
  const [vulnerabilities, setVulnerabilities] = useState(null);
  const [auditLog, setAuditLog] = useState([]);
  const [recommendations, setRecommendations] = useState([]);
  const [detailsDialog, setDetailsDialog] = useState(null);
  const [auditFilters, setAuditFilters] = useState({
    action: '',
    result: '',
    limit: 50
  });

  useEffect(() => {
    if (token && user?.role === 'admin') {
      fetchSecurityStatus();
      fetchRecommendations();
    }
  }, [token, user]);

  useEffect(() => {
    if (tabValue === 2 && token && user?.role === 'admin') {
      fetchAuditLog();
    }
  }, [tabValue, auditFilters, token, user]);

  const fetchSecurityStatus = async () => {
    try {
      setLoading(true);
      const response = await axios.get('/api/security-monitor/status', {
        headers: { Authorization: `Bearer ${token}` }
      });
      setSecurityStatus(response.data);
    } catch (error) {
      // Only show error if not authentication related
      if (error.response?.status !== 401) {
        console.error('Error fetching security status:', error);
        notifySecurityError('Failed to load security status');
      }
    } finally {
      setLoading(false);
    }
  };

  const fetchVulnerabilities = async () => {
    try {
      const response = await axios.get('/api/security-monitor/vulnerabilities/detailed', {
        headers: { Authorization: `Bearer ${token}` }
      });
      setVulnerabilities(response.data);
    } catch (error) {
      // Only show error if not authentication related
      if (error.response?.status !== 401) {
        console.error('Error fetching vulnerabilities:', error);
        notifySecurityError('Failed to load vulnerability details');
      }
    }
  };

  const fetchAuditLog = async () => {
    try {
      const params = new URLSearchParams();
      if (auditFilters.action) params.append('action', auditFilters.action);
      if (auditFilters.result) params.append('result', auditFilters.result);
      params.append('limit', auditFilters.limit);

      const response = await axios.get(`/api/security-monitor/audit-log?${params}`, {
        headers: { Authorization: `Bearer ${token}` }
      });
      setAuditLog(response.data.logs || []);
    } catch (error) {
      // Only show error if not authentication related
      if (error.response?.status !== 401) {
        console.error('Error fetching audit log:', error);
        notifySecurityError('Failed to load audit log');
      }
    }
  };

  const fetchRecommendations = async () => {
    try {
      const response = await axios.get('/api/security-monitor/recommendations', {
        headers: { Authorization: `Bearer ${token}` }
      });
      setRecommendations(response.data.recommendations || []);
    } catch (error) {
      // Silently fail for authentication errors
      if (error.response?.status !== 401) {
        console.error('Error fetching recommendations:', error);
      }
    }
  };

  const handleExportAuditLog = async (format) => {
    try {
      const response = await axios.get(`/api/security-monitor/audit-log/export?format=${format}`, {
        headers: { Authorization: `Bearer ${token}` },
        responseType: format === 'csv' ? 'text' : 'json'
      });

      const blob = new Blob([format === 'csv' ? response.data : JSON.stringify(response.data, null, 2)], {
        type: format === 'csv' ? 'text/csv' : 'application/json'
      });
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `security-audit-${Date.now()}.${format}`;
      link.click();
      
      notifySecuritySuccess('Audit log exported successfully');
    } catch (error) {
      console.error('Error exporting audit log:', error);
      notifySecurityError('Failed to export audit log');
    }
  };

  const getSeverityColor = (severity) => {
    switch (severity) {
      case 'critical': return 'error';
      case 'high': return 'error';
      case 'warning': return 'warning';
      case 'moderate': return 'warning';
      case 'low': return 'info';
      case 'info': return 'info';
      default: return 'default';
    }
  };

  const getSeverityIcon = (severity) => {
    switch (severity) {
      case 'critical':
      case 'high':
        return <ErrorIcon color="error" />;
      case 'warning':
      case 'moderate':
        return <Warning color="warning" />;
      case 'low':
      case 'info':
        return <Info color="info" />;
      default:
        return <CheckCircle color="success" />;
    }
  };

  if (user?.role !== 'admin') {
    return (
      <Container maxWidth="md" sx={{ mt: 4 }}>
        <Alert severity="error">
          {t('security.adminAccessRequired')}
        </Alert>
      </Container>
    );
  }

  if (loading) {
    return (
      <Container maxWidth="lg" sx={{ mt: 4, display: 'flex', justifyContent: 'center' }}>
        <CircularProgress />
      </Container>
    );
  }

  return (
    <Container maxWidth="xl" sx={{ mt: 4, mb: 4 }}>
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
        <Typography variant="h4" sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
          <Shield color="primary" />
          {t('security.monitoring')}
        </Typography>
        <Box sx={{ display: 'flex', gap: 2 }}>
          <Button
            variant="outlined"
            startIcon={<ArrowBack />}
            onClick={() => navigate('/security')}
          >
            {t('backToSecurity')}
          </Button>
          <Button
            variant="outlined"
            startIcon={<Refresh />}
            onClick={fetchSecurityStatus}
          >
            {t('refresh')}
          </Button>
        </Box>
      </Box>

      {/* Recommendations Alert */}
      {recommendations.length > 0 && (
        <Alert 
          severity={recommendations.some(r => r.severity === 'high') ? 'error' : 'warning'}
          sx={{ mb: 3 }}
        >
          <Typography variant="subtitle2" sx={{ fontWeight: 600, mb: 1 }}>
            {t('security.securityRecommendations')}
          </Typography>
          {recommendations.slice(0, 3).map((rec, index) => (
            <Box key={index} sx={{ mt: 1 }}>
              • {rec.description}
            </Box>
          ))}
          {recommendations.length > 3 && (
            <Typography variant="body2" sx={{ mt: 1, fontStyle: 'italic' }}>
              +{recommendations.length - 3} {t('security.moreRecommendations')}
            </Typography>
          )}
        </Alert>
      )}

      {/* Key Metrics */}
      <Grid container spacing={3} sx={{ mb: 3 }}>
        <Grid item xs={12} sm={6} md={3}>
          <Card>
            <CardContent>
              <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <Box>
                  <Typography variant="caption" color="text.secondary">
                    {t('security.totalVulnerabilities')}
                  </Typography>
                  <Typography variant="h4">
                    {(securityStatus?.vulnerabilities?.backend?.total || 0) + 
                     (securityStatus?.vulnerabilities?.frontend?.total || 0)}
                  </Typography>
                </Box>
                <BugReport color={
                  ((securityStatus?.vulnerabilities?.backend?.critical || 0) + 
                   (securityStatus?.vulnerabilities?.frontend?.critical || 0)) > 0 
                    ? 'error' 
                    : 'success'
                } sx={{ fontSize: 40 }} />
              </Box>
            </CardContent>
          </Card>
        </Grid>

        <Grid item xs={12} sm={6} md={3}>
          <Card>
            <CardContent>
              <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <Box>
                  <Typography variant="caption" color="text.secondary">
                    {t('security.activeSessions')}
                  </Typography>
                  <Typography variant="h4">
                    {securityStatus?.systemHealth?.activeSessions || 0}
                  </Typography>
                </Box>
                <AccountCircle color="primary" sx={{ fontSize: 40 }} />
              </Box>
            </CardContent>
          </Card>
        </Grid>

        <Grid item xs={12} sm={6} md={3}>
          <Card>
            <CardContent>
              <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <Box>
                  <Typography variant="caption" color="text.secondary">
                    {t('security.failedLogins')} (1h)
                  </Typography>
                  <Typography variant="h4">
                    {securityStatus?.systemHealth?.failedLogins || 0}
                  </Typography>
                </Box>
                <Lock color={
                  (securityStatus?.systemHealth?.failedLogins || 0) > 10 ? 'error' : 'success'
                } sx={{ fontSize: 40 }} />
              </Box>
            </CardContent>
          </Card>
        </Grid>

        <Grid item xs={12} sm={6} md={3}>
          <Card>
            <CardContent>
              <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <Box>
                  <Typography variant="caption" color="text.secondary">
                    {t('security.lockedAccounts')}
                  </Typography>
                  <Typography variant="h4">
                    {securityStatus?.systemHealth?.lockedAccounts || 0}
                  </Typography>
                </Box>
                <VpnKey color={
                  (securityStatus?.systemHealth?.lockedAccounts || 0) > 0 ? 'warning' : 'success'
                } sx={{ fontSize: 40 }} />
              </Box>
            </CardContent>
          </Card>
        </Grid>
      </Grid>

      {/* Tabs */}
      <Paper sx={{ mb: 3 }}>
        <Tabs value={tabValue} onChange={(e, v) => setTabValue(v)} variant="fullWidth">
          <Tab label={t('security.overview')} icon={<Assessment />} iconPosition="start" />
          <Tab label={t('security.vulnerabilities')} icon={<BugReport />} iconPosition="start" />
          <Tab label={t('security.auditLog')} icon={<Description />} iconPosition="start" />
          <Tab label={t('security.recommendations')} icon={<Info />} iconPosition="start" />
        </Tabs>
      </Paper>

      {/* Overview Tab */}
      <TabPanel value={tabValue} index={0}>
        <Grid container spacing={3}>
          {/* Dependencies Status */}
          <Grid item xs={12} md={6}>
            <Card>
              <CardContent>
                <Typography variant="h6" sx={{ mb: 2, display: 'flex', alignItems: 'center', gap: 1 }}>
                  <Description color="primary" />
                  {t('security.dependencies')}
                </Typography>
                <List>
                  <ListItem>
                    <ListItemIcon>
                      <CheckCircle color="success" />
                    </ListItemIcon>
                    <ListItemText
                      primary={t('security.backend')}
                      secondary={`${securityStatus?.dependencies?.backend?.dependencies || 0} dependencies, ${securityStatus?.dependencies?.backend?.devDependencies || 0} dev dependencies`}
                    />
                  </ListItem>
                  <ListItem>
                    <ListItemIcon>
                      <CheckCircle color="success" />
                    </ListItemIcon>
                    <ListItemText
                      primary={t('security.frontend')}
                      secondary={`${securityStatus?.dependencies?.frontend?.dependencies || 0} dependencies, ${securityStatus?.dependencies?.frontend?.devDependencies || 0} dev dependencies`}
                    />
                  </ListItem>
                </List>
              </CardContent>
            </Card>
          </Grid>

          {/* Security Headers */}
          <Grid item xs={12} md={6}>
            <Card>
              <CardContent>
                <Typography variant="h6" sx={{ mb: 2, display: 'flex', alignItems: 'center', gap: 1 }}>
                  <Shield color="primary" />
                  {t('security.securityHeaders')}
                </Typography>
                <List>
                  {securityStatus?.securityHeaders?.helmet?.features?.map((feature, index) => (
                    <ListItem key={index}>
                      <ListItemIcon>
                        <CheckCircle color="success" fontSize="small" />
                      </ListItemIcon>
                      <ListItemText primary={feature} />
                    </ListItem>
                  ))}
                </List>
              </CardContent>
            </Card>
          </Grid>

          {/* Recent Security Events */}
          <Grid item xs={12}>
            <Card>
              <CardContent>
                <Typography variant="h6" sx={{ mb: 2 }}>
                  {t('security.recentEvents')}
                </Typography>
                <TableContainer>
                  <Table size="small">
                    <TableHead>
                      <TableRow>
                        <TableCell>{t('security.eventType')}</TableCell>
                        <TableCell>{t('security.status')}</TableCell>
                        <TableCell align="right">{t('count')}</TableCell>
                        <TableCell>{t('security.lastOccurrence')}</TableCell>
                      </TableRow>
                    </TableHead>
                    <TableBody>
                      {Array.isArray(securityStatus?.auditSummary) && securityStatus.auditSummary.slice(0, 10).map((event, index) => (
                        <TableRow key={index}>
                          <TableCell>{event.action}</TableCell>
                          <TableCell>
                            <Chip
                              label={event.result}
                              color={event.result === 'success' ? 'success' : 'error'}
                              size="small"
                            />
                          </TableCell>
                          <TableCell align="right">{event.count}</TableCell>
                          <TableCell>
                            {event.last_occurrence ? format(new Date(event.last_occurrence), 'PPpp') : '-'}
                          </TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                </TableContainer>
              </CardContent>
            </Card>
          </Grid>
        </Grid>
      </TabPanel>

      {/* Vulnerabilities Tab */}
      <TabPanel value={tabValue} index={1}>
        <Box sx={{ mb: 2 }}>
          <Button
            variant="outlined"
            startIcon={<Refresh />}
            onClick={fetchVulnerabilities}
          >
            {t('security.scanVulnerabilities')}
          </Button>
        </Box>

        {vulnerabilities ? (
          <Grid container spacing={3}>
            {/* Backend Vulnerabilities */}
            <Grid item xs={12} md={6}>
              <Card>
                <CardContent>
                  <Typography variant="h6" sx={{ mb: 2 }}>
                    {t('security.backend')} {t('security.vulnerabilities')}
                  </Typography>
                  {vulnerabilities.backend?.metadata?.vulnerabilities ? (
                    <>
                      <Grid container spacing={2}>
                        {['critical', 'high', 'moderate', 'low'].map((severity) => (
                          <Grid item xs={6} key={severity}>
                            <Box sx={{ textAlign: 'center', p: 2, border: 1, borderColor: 'divider', borderRadius: 1 }}>
                              <Typography variant="h4" color={getSeverityColor(severity)}>
                                {vulnerabilities.backend.metadata.vulnerabilities[severity] || 0}
                              </Typography>
                              <Typography variant="caption" textTransform="capitalize">
                                {severity}
                              </Typography>
                            </Box>
                          </Grid>
                        ))}
                      </Grid>
                    </>
                  ) : (
                    <Alert severity="success">{t('security.noVulnerabilities')}</Alert>
                  )}
                </CardContent>
              </Card>
            </Grid>

            {/* Frontend Vulnerabilities */}
            <Grid item xs={12} md={6}>
              <Card>
                <CardContent>
                  <Typography variant="h6" sx={{ mb: 2 }}>
                    {t('security.frontend')} {t('security.vulnerabilities')}
                  </Typography>
                  {vulnerabilities.frontend?.metadata?.vulnerabilities ? (
                    <>
                      <Grid container spacing={2}>
                        {['critical', 'high', 'moderate', 'low'].map((severity) => (
                          <Grid item xs={6} key={severity}>
                            <Box sx={{ textAlign: 'center', p: 2, border: 1, borderColor: 'divider', borderRadius: 1 }}>
                              <Typography variant="h4" color={getSeverityColor(severity)}>
                                {vulnerabilities.frontend.metadata.vulnerabilities[severity] || 0}
                              </Typography>
                              <Typography variant="caption" textTransform="capitalize">
                                {severity}
                              </Typography>
                            </Box>
                          </Grid>
                        ))}
                      </Grid>
                    </>
                  ) : (
                    <Alert severity="success">{t('security.noVulnerabilities')}</Alert>
                  )}
                </CardContent>
              </Card>
            </Grid>
          </Grid>
        ) : (
          <Alert severity="info">
            {t('security.clickToScanVulnerabilities')}
          </Alert>
        )}
      </TabPanel>

      {/* Audit Log Tab */}
      <TabPanel value={tabValue} index={2}>
        <Box sx={{ mb: 2, display: 'flex', gap: 2, flexWrap: 'wrap' }}>
          <FormControl size="small" sx={{ minWidth: 150 }}>
            <InputLabel>{t('security.action')}</InputLabel>
            <Select
              value={auditFilters.action}
              label={t('security.action')}
              onChange={(e) => setAuditFilters({ ...auditFilters, action: e.target.value })}
            >
              <MenuItem value="">{t('all')}</MenuItem>
              <MenuItem value="login">Login</MenuItem>
              <MenuItem value="logout">Logout</MenuItem>
              <MenuItem value="registration">Registration</MenuItem>
              <MenuItem value="password_change">Password Change</MenuItem>
              <MenuItem value="2fa">2FA</MenuItem>
              <MenuItem value="token_issued">Token Issued</MenuItem>
              <MenuItem value="token_refreshed">Token Refreshed</MenuItem>
              <MenuItem value="token_revoked">Token Revoked</MenuItem>
              <MenuItem value="privilege_change">Privilege Change</MenuItem>
              <MenuItem value="permission_granted">Permission Granted</MenuItem>
              <MenuItem value="permission_revoked">Permission Revoked</MenuItem>
              <MenuItem value="account_status_change">Account Status Change</MenuItem>
              <MenuItem value="admin_activity">Admin Activity</MenuItem>
              <MenuItem value="sensitive_data_access">Sensitive Data Access</MenuItem>
            </Select>
          </FormControl>

          <FormControl size="small" sx={{ minWidth: 150 }}>
            <InputLabel>{t('security.status')}</InputLabel>
            <Select
              value={auditFilters.result}
              label={t('security.status')}
              onChange={(e) => setAuditFilters({ ...auditFilters, result: e.target.value })}
            >
              <MenuItem value="">{t('all')}</MenuItem>
              <MenuItem value="success">Success</MenuItem>
              <MenuItem value="failed">Failed</MenuItem>
              <MenuItem value="blocked">Blocked</MenuItem>
            </Select>
          </FormControl>

          <Box sx={{ flexGrow: 1 }} />

          <Button
            variant="outlined"
            startIcon={<Download />}
            onClick={() => handleExportAuditLog('json')}
          >
            Export JSON
          </Button>
          <Button
            variant="outlined"
            startIcon={<Download />}
            onClick={() => handleExportAuditLog('csv')}
          >
            Export CSV
          </Button>
        </Box>

        <TableContainer component={Paper}>
          <Table>
            <TableHead>
              <TableRow>
                <TableCell>{t('security.timestamp')}</TableCell>
                <TableCell>{t('security.action')}</TableCell>
                <TableCell>{t('security.status')}</TableCell>
                <TableCell>{t('security.ipAddress')}</TableCell>
                <TableCell>{t('actions')}</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {auditLog.map((log) => (
                <TableRow key={log.id}>
                  <TableCell>{format(new Date(log.timestamp), 'PPpp')}</TableCell>
                  <TableCell>{log.action}</TableCell>
                  <TableCell>
                    <Chip
                      label={log.result}
                      color={log.result === 'success' ? 'success' : 'error'}
                      size="small"
                    />
                  </TableCell>
                  <TableCell>{log.ip_address || '-'}</TableCell>
                  <TableCell>
                    <IconButton
                      size="small"
                      onClick={() => setDetailsDialog(log)}
                    >
                      <Visibility />
                    </IconButton>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </TableContainer>
      </TabPanel>

      {/* Recommendations Tab */}
      <TabPanel value={tabValue} index={3}>
        {recommendations.length === 0 ? (
          <Alert severity="success">
            {t('security.noRecommendations')}
          </Alert>
        ) : (
          <Grid container spacing={2}>
            {recommendations.map((rec, index) => (
              <Grid item xs={12} key={index}>
                <Card>
                  <CardContent>
                    <Box sx={{ display: 'flex', gap: 2 }}>
                      <Box>{getSeverityIcon(rec.severity)}</Box>
                      <Box sx={{ flexGrow: 1 }}>
                        <Typography variant="h6" sx={{ mb: 1 }}>
                          {rec.title}
                        </Typography>
                        <Typography variant="body2" color="text.secondary" sx={{ mb: 1 }}>
                          {rec.description}
                        </Typography>
                        <Chip label={rec.category} size="small" sx={{ mr: 1 }} />
                        <Chip label={rec.severity} color={getSeverityColor(rec.severity)} size="small" />
                        <Divider sx={{ my: 2 }} />
                        <Typography variant="body2" fontWeight={600}>
                          {t('security.recommendedAction')}:
                        </Typography>
                        <Typography variant="body2">{rec.action}</Typography>
                      </Box>
                    </Box>
                  </CardContent>
                </Card>
              </Grid>
            ))}
          </Grid>
        )}
      </TabPanel>

      {/* Details Dialog */}
      <Dialog
        open={!!detailsDialog}
        onClose={() => setDetailsDialog(null)}
        maxWidth="md"
        fullWidth
      >
        <DialogTitle>{t('security.eventDetails')}</DialogTitle>
        <DialogContent>
          {detailsDialog && (() => {
            const details = detailsDialog.details ? JSON.parse(detailsDialog.details) : {};
            const metadata = details.metadata || {};

            return (
              <Box>
                <Grid container spacing={2}>
                  <Grid item xs={6}>
                    <Typography variant="subtitle2" color="text.secondary">
                      {t('security.timestamp')}
                    </Typography>
                    <Typography>{format(new Date(detailsDialog.timestamp), 'PPpp')}</Typography>
                  </Grid>
                  <Grid item xs={6}>
                    <Typography variant="subtitle2" color="text.secondary">
                      {t('security.action')}
                    </Typography>
                    <Typography>{detailsDialog.action}</Typography>
                  </Grid>
                  <Grid item xs={6}>
                    <Typography variant="subtitle2" color="text.secondary">
                      {t('security.status')}
                    </Typography>
                    <Chip label={detailsDialog.result} color={detailsDialog.result === 'success' ? 'success' : 'error'} />
                  </Grid>
                  <Grid item xs={6}>
                    <Typography variant="subtitle2" color="text.secondary">
                      {t('security.ipAddress')}
                    </Typography>
                    <Typography sx={{ fontFamily: 'monospace' }}>{detailsDialog.ip_address || '-'}</Typography>
                  </Grid>

                  {/* Device Information - CWE-778 */}
                  {metadata.deviceInfo && (
                    <>
                      <Grid item xs={12}>
                        <Divider sx={{ my: 1 }} />
                        <Typography variant="subtitle1" sx={{ mb: 1 }}>
                          {t('security.deviceInformation')}
                        </Typography>
                      </Grid>
                      <Grid item xs={4}>
                        <Typography variant="subtitle2" color="text.secondary">
                          {t('security.deviceType')}
                        </Typography>
                        <Typography textTransform="capitalize">{metadata.deviceInfo.deviceType || '-'}</Typography>
                      </Grid>
                      <Grid item xs={4}>
                        <Typography variant="subtitle2" color="text.secondary">
                          {t('security.operatingSystem')}
                        </Typography>
                        <Typography>{metadata.deviceInfo.os || '-'}</Typography>
                      </Grid>
                      <Grid item xs={4}>
                        <Typography variant="subtitle2" color="text.secondary">
                          {t('security.browser')}
                        </Typography>
                        <Typography>{metadata.deviceInfo.browser || '-'}</Typography>
                      </Grid>
                    </>
                  )}

                  {/* Token Details - CWE-778 */}
                  {(metadata.tokenType || metadata.purpose || metadata.expiresIn) && (
                    <>
                      <Grid item xs={12}>
                        <Divider sx={{ my: 1 }} />
                        <Typography variant="subtitle1" sx={{ mb: 1 }}>
                          {t('security.tokenDetails')}
                        </Typography>
                      </Grid>
                      {metadata.tokenType && (
                        <Grid item xs={4}>
                          <Typography variant="subtitle2" color="text.secondary">
                            {t('security.tokenType')}
                          </Typography>
                          <Chip label={metadata.tokenType} size="small" />
                        </Grid>
                      )}
                      {metadata.purpose && (
                        <Grid item xs={4}>
                          <Typography variant="subtitle2" color="text.secondary">
                            {t('security.purpose')}
                          </Typography>
                          <Typography textTransform="capitalize">{metadata.purpose.replace(/_/g, ' ')}</Typography>
                        </Grid>
                      )}
                      {metadata.expiresIn && (
                        <Grid item xs={4}>
                          <Typography variant="subtitle2" color="text.secondary">
                            {t('security.expiresIn')}
                          </Typography>
                          <Typography>{metadata.expiresIn}</Typography>
                        </Grid>
                      )}
                      {metadata.reason && (
                        <Grid item xs={12}>
                          <Typography variant="subtitle2" color="text.secondary">
                            {t('security.reason')}
                          </Typography>
                          <Typography textTransform="capitalize">{metadata.reason.replace(/_/g, ' ')}</Typography>
                        </Grid>
                      )}
                    </>
                  )}

                  {/* Privilege Change Details - CWE-778 */}
                  {(metadata.previousRole || metadata.newRole || metadata.changedBy) && (
                    <>
                      <Grid item xs={12}>
                        <Divider sx={{ my: 1 }} />
                        <Typography variant="subtitle1" sx={{ mb: 1 }}>
                          {t('security.privilegeChangeDetails')}
                        </Typography>
                      </Grid>
                      {metadata.targetUsername && (
                        <Grid item xs={12}>
                          <Typography variant="subtitle2" color="text.secondary">
                            {t('security.affectedUser')}
                          </Typography>
                          <Typography fontWeight="bold">{metadata.targetUsername}</Typography>
                        </Grid>
                      )}
                      <Grid item xs={6}>
                        <Typography variant="subtitle2" color="text.secondary">
                          {t('security.previousRole')}
                        </Typography>
                        <Chip label={metadata.previousRole || '-'} size="small" color="default" />
                      </Grid>
                      <Grid item xs={6}>
                        <Typography variant="subtitle2" color="text.secondary">
                          {t('security.newRole')}
                        </Typography>
                        <Chip label={metadata.newRole || '-'} size="small" color="primary" />
                      </Grid>
                      {metadata.changedByUsername && (
                        <Grid item xs={12}>
                          <Typography variant="subtitle2" color="text.secondary">
                            {t('security.changedBy')}
                          </Typography>
                          <Typography>{metadata.changedByUsername}</Typography>
                        </Grid>
                      )}
                    </>
                  )}

                  {/* Account Status Change Details - CWE-778 */}
                  {(metadata.previousStatus || metadata.newStatus) && (
                    <>
                      <Grid item xs={12}>
                        <Divider sx={{ my: 1 }} />
                        <Typography variant="subtitle1" sx={{ mb: 1 }}>
                          {t('security.accountStatusDetails')}
                        </Typography>
                      </Grid>
                      {metadata.targetUsername && (
                        <Grid item xs={12}>
                          <Typography variant="subtitle2" color="text.secondary">
                            {t('security.affectedUser')}
                          </Typography>
                          <Typography fontWeight="bold">{metadata.targetUsername}</Typography>
                        </Grid>
                      )}
                      <Grid item xs={6}>
                        <Typography variant="subtitle2" color="text.secondary">
                          {t('security.previousStatus')}
                        </Typography>
                        <Chip 
                          label={metadata.previousStatus || '-'} 
                          size="small" 
                          color={metadata.previousStatus === 'active' ? 'success' : 'default'} 
                        />
                      </Grid>
                      <Grid item xs={6}>
                        <Typography variant="subtitle2" color="text.secondary">
                          {t('security.newStatus')}
                        </Typography>
                        <Chip 
                          label={metadata.newStatus || '-'} 
                          size="small" 
                          color={metadata.newStatus === 'active' ? 'success' : 'error'} 
                        />
                      </Grid>
                      {metadata.changedByUsername && (
                        <Grid item xs={12}>
                          <Typography variant="subtitle2" color="text.secondary">
                            {t('security.changedBy')}
                          </Typography>
                          <Typography>{metadata.changedByUsername}</Typography>
                        </Grid>
                      )}
                      {metadata.reason && (
                        <Grid item xs={12}>
                          <Typography variant="subtitle2" color="text.secondary">
                            {t('security.reason')}
                          </Typography>
                          <Typography textTransform="capitalize">{metadata.reason.replace(/_/g, ' ')}</Typography>
                        </Grid>
                      )}
                    </>
                  )}

                  {/* Admin Activity Details - CWE-778 */}
                  {(metadata.action === 'user_created' || metadata.action === 'user_deleted' || 
                    metadata.action === 'account_unlocked' || metadata.action === 'password_reset' || 
                    metadata.action === 'force_logout' || metadata.adminUsername) && (
                    <>
                      <Grid item xs={12}>
                        <Divider sx={{ my: 1 }} />
                        <Typography variant="subtitle1" sx={{ mb: 1 }}>
                          {t('security.adminAction')}
                        </Typography>
                      </Grid>
                      {metadata.action && (
                        <Grid item xs={12}>
                          <Typography variant="subtitle2" color="text.secondary">
                            {t('security.action')}
                          </Typography>
                          <Chip label={metadata.action.replace(/_/g, ' ')} size="small" color="warning" sx={{ textTransform: 'capitalize' }} />
                        </Grid>
                      )}
                      {metadata.adminUsername && (
                        <Grid item xs={6}>
                          <Typography variant="subtitle2" color="text.secondary">
                            {t('security.adminAction')}
                          </Typography>
                          <Typography fontWeight="bold">{metadata.adminUsername}</Typography>
                        </Grid>
                      )}
                      {metadata.targetUsername && (
                        <Grid item xs={6}>
                          <Typography variant="subtitle2" color="text.secondary">
                            {t('security.affectedUser')}
                          </Typography>
                          <Typography fontWeight="bold">{metadata.targetUsername}</Typography>
                        </Grid>
                      )}
                      {metadata.changes && (
                        <Grid item xs={12}>
                          <Typography variant="subtitle2" color="text.secondary">
                            {t('details')}
                          </Typography>
                          <Paper variant="outlined" sx={{ p: 1, mt: 0.5, bgcolor: 'action.hover' }}>
                            <Typography variant="caption" component="pre" sx={{ whiteSpace: 'pre-wrap', fontFamily: 'monospace' }}>
                              {JSON.stringify(metadata.changes, null, 2)}
                            </Typography>
                          </Paper>
                        </Grid>
                      )}
                    </>
                  )}

                  {/* Sensitive Data Access Details - CWE-778 */}
                  {metadata.dataType && (
                    <>
                      <Grid item xs={12}>
                        <Divider sx={{ my: 1 }} />
                        <Typography variant="subtitle1" sx={{ mb: 1 }}>
                          {t('security.sensitiveDataAccess')}
                        </Typography>
                      </Grid>
                      <Grid item xs={6}>
                        <Typography variant="subtitle2" color="text.secondary">
                          {t('security.dataType')}
                        </Typography>
                        <Chip label={metadata.dataType.replace(/_/g, ' ')} size="small" color="info" sx={{ textTransform: 'capitalize' }} />
                      </Grid>
                      <Grid item xs={6}>
                        <Typography variant="subtitle2" color="text.secondary">
                          {t('security.accessMethod')}
                        </Typography>
                        <Typography textTransform="capitalize">{metadata.accessMethod || 'view'}</Typography>
                      </Grid>
                      {metadata.recordCount !== undefined && (
                        <Grid item xs={6}>
                          <Typography variant="subtitle2" color="text.secondary">
                            {t('records')}
                          </Typography>
                          <Typography>{metadata.recordCount}</Typography>
                        </Grid>
                      )}
                      {metadata.scope && (
                        <Grid item xs={6}>
                          <Typography variant="subtitle2" color="text.secondary">
                            {t('scope')}
                          </Typography>
                          <Typography textTransform="capitalize">{metadata.scope}</Typography>
                        </Grid>
                      )}
                    </>
                  )}

                  {/* User Agent (if no parsed device info) */}
                  {detailsDialog.user_agent && !metadata.deviceInfo && (
                    <Grid item xs={12}>
                      <Typography variant="subtitle2" color="text.secondary">
                        {t('security.userAgent')}
                      </Typography>
                      <Typography 
                        variant="caption" 
                        sx={{ 
                          fontFamily: 'monospace', 
                          wordBreak: 'break-all',
                          display: 'block',
                          bgcolor: 'action.hover',
                          p: 1,
                          borderRadius: 1,
                          mt: 0.5
                        }}
                      >
                        {detailsDialog.user_agent}
                      </Typography>
                    </Grid>
                  )}

                  {/* Raw Details (fallback) */}
                  {detailsDialog.details && Object.keys(details).length > 0 && (
                    <Grid item xs={12}>
                      <Divider sx={{ my: 1 }} />
                      <Typography variant="subtitle2" color="text.secondary" sx={{ mb: 1 }}>
                        {t('security.rawDetails')}
                      </Typography>
                      <Paper variant="outlined" sx={{ p: 2, bgcolor: 'background.default' }}>
                        <pre style={{ margin: 0, whiteSpace: 'pre-wrap', fontSize: '0.75rem' }}>
                          {JSON.stringify(details, null, 2)}
                        </pre>
                      </Paper>
                    </Grid>
                  )}
                </Grid>
              </Box>
            );
          })()}
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDetailsDialog(null)}>{t('close')}</Button>
        </DialogActions>
      </Dialog>
    </Container>
  );
};

export default SecurityMonitor;
