/**
 * Security Intelligence Dashboard
 * Real-time SIEM monitoring, anomaly detection, and threat intelligence
 */

import React, { useState, useEffect, useCallback } from 'react';
import {
  Box,
  Container,
  Paper,
  Typography,
  Grid,
  Card,
  CardContent,
  Chip,
  Alert,
  CircularProgress,
  Button,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  IconButton,
  Tooltip,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  List,
  ListItem,
  ListItemText,
  Divider,
  TextField,
  LinearProgress,
  Badge,
  Tabs,
  Tab
} from '@mui/material';
import {
  Security,
  Warning,
  Error as ErrorIcon,
  Info,
  CheckCircle,
  Refresh,
  Download,
  ArrowBack,
  Timeline,
  Shield,
  BugReport,
  Visibility,
  Assessment,
  Notifications,
  CheckCircleOutline,
  Close
} 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 }) => (
  <div role="tabpanel" hidden={value !== index}>
    {value === index && <Box sx={{ py: 3 }}>{children}</Box>}
  </div>
);

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

  const [loading, setLoading] = useState(true);
  const [tabValue, setTabValue] = useState(0);
  const [dashboardData, setDashboardData] = useState(null);
  const [anomalies, setAnomalies] = useState([]);
  const [alerts, setAlerts] = useState([]);
  const [threats, setThreats] = useState([]);
  const [logs, setLogs] = useState([]);
  const [selectedItem, setSelectedItem] = useState(null);
  const [detailsDialog, setDetailsDialog] = useState(false);
  const [refreshInterval, setRefreshInterval] = useState(null);

  // Fetch dashboard data
  const fetchDashboardData = useCallback(async () => {
    try {
      const response = await axios.get('/api/siem/dashboard', {
        headers: { Authorization: `Bearer ${token}` }
      });

      if (response.data.success) {
        setDashboardData(response.data.data);
      }
    } catch (error) {
      console.error('Failed to fetch dashboard data:', error);
    }
  }, [token]);

  // Fetch anomalies
  const fetchAnomalies = useCallback(async (status = 'open') => {
    try {
      const response = await axios.get('/api/siem/anomalies', {
        params: { status, limit: 100 },
        headers: { Authorization: `Bearer ${token}` }
      });

      if (response.data.success) {
        setAnomalies(response.data.data);
      }
    } catch (error) {
      console.error('Failed to fetch anomalies:', error);
    }
  }, [token]);

  // Fetch alerts
  const fetchAlerts = useCallback(async (status = 'active') => {
    try {
      const response = await axios.get('/api/siem/alerts', {
        params: { status, limit: 100 },
        headers: { Authorization: `Bearer ${token}` }
      });

      if (response.data.success) {
        setAlerts(response.data.data);
      }
    } catch (error) {
      console.error('Failed to fetch alerts:', error);
    }
  }, [token]);

  // Fetch threat intelligence
  const fetchThreats = useCallback(async () => {
    try {
      const response = await axios.get('/api/siem/threats', {
        params: { limit: 50 },
        headers: { Authorization: `Bearer ${token}` }
      });

      if (response.data.success) {
        setThreats(response.data.data);
      }
    } catch (error) {
      console.error('Failed to fetch threats:', error);
    }
  }, [token]);

  // Fetch logs
  const fetchLogs = useCallback(async () => {
    try {
      const response = await axios.get('/api/siem/logs', {
        params: { limit: 50 },
        headers: { Authorization: `Bearer ${token}` }
      });

      if (response.data.success) {
        setLogs(response.data.data);
      }
    } catch (error) {
      console.error('Failed to fetch logs:', error);
    }
  }, [token]);

  // Acknowledge alert
  const handleAcknowledgeAlert = async (alertId) => {
    try {
      await axios.post(`/api/siem/alerts/${alertId}/acknowledge`, {}, {
        headers: { Authorization: `Bearer ${token}` }
      });

      notifySecuritySuccess(t('siem.alertAcknowledged'));
      fetchAlerts();
    } catch (error) {
      notifySecurityError(t('siem.alertAcknowledgeFailed'));
    }
  };

  // Resolve alert
  const handleResolveAlert = async (alertId, notes) => {
    try {
      await axios.post(`/api/siem/alerts/${alertId}/resolve`, 
        { notes },
        { headers: { Authorization: `Bearer ${token}` } }
      );

      notifySecuritySuccess(t('siem.alertResolved'));
      fetchAlerts();
      setDetailsDialog(false);
    } catch (error) {
      notifySecurityError(t('siem.alertResolveFailed'));
    }
  };

  // Resolve anomaly
  const handleResolveAnomaly = async (anomalyId, notes) => {
    try {
      await axios.post(`/api/siem/anomalies/${anomalyId}/resolve`,
        { notes },
        { headers: { Authorization: `Bearer ${token}` } }
      );

      notifySecuritySuccess(t('siem.anomalyResolved'));
      fetchAnomalies();
      setDetailsDialog(false);
    } catch (error) {
      notifySecurityError(t('siem.anomalyResolveFailed'));
    }
  };

  // Export logs
  const handleExport = async (format = 'json') => {
    try {
      const response = await axios.get('/api/siem/export', {
        params: { format },
        headers: { Authorization: `Bearer ${token}` },
        responseType: 'blob'
      });

      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', `siem_export_${Date.now()}.${format}`);
      document.body.appendChild(link);
      link.click();
      link.remove();

      notifySecuritySuccess(t('siem.exportSuccess'));
    } catch (error) {
      notifySecurityError(t('siem.exportFailed'));
    }
  };

  // Verify log integrity
  const handleVerifyIntegrity = async () => {
    try {
      setLoading(true);
      const response = await axios.post('/api/siem/logs/verify', {}, {
        headers: { Authorization: `Bearer ${token}` }
      });

      if (response.data.success) {
        const { verified, tampered, total } = response.data.data;
        if (tampered > 0) {
          notifySecurityError(t('siem.integrityCompromised', { tampered, total }));
        } else {
          notifySecuritySuccess(t('siem.integrityVerified', { verified }));
        }
      }
    } catch (error) {
      notifySecurityError(t('siem.integrityCheckFailed'));
    } finally {
      setLoading(false);
    }
  };

  // Initialize
  useEffect(() => {
    const loadData = async () => {
      setLoading(true);
      await Promise.all([
        fetchDashboardData(),
        fetchAnomalies(),
        fetchAlerts(),
        fetchThreats(),
        fetchLogs()
      ]);
      setLoading(false);
    };

    loadData();

    // Auto-refresh every 60 seconds
    const interval = setInterval(() => {
      fetchDashboardData();
      fetchAnomalies();
      fetchAlerts();
    }, 60000);

    setRefreshInterval(interval);

    return () => {
      if (interval) clearInterval(interval);
    };
  }, [fetchDashboardData, fetchAnomalies, fetchAlerts, fetchThreats, fetchLogs]);

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

  // Get threat score color
  const getThreatScoreColor = (score) => {
    if (score >= 80) return 'error';
    if (score >= 50) return 'warning';
    if (score >= 20) return 'info';
    return 'success';
  };

  if (loading && !dashboardData) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', minHeight: '80vh' }}>
        <CircularProgress />
      </Box>
    );
  }

  return (
    <Container maxWidth="xl">
      <Box sx={{ py: 4 }}>
        {/* Header */}
        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
            <IconButton onClick={() => navigate('/security')}>
              <ArrowBack />
            </IconButton>
            <Shield sx={{ fontSize: 40, color: 'primary.main' }} />
            <Typography variant="h4" component="h1">
              {t('siem.title')}
            </Typography>
          </Box>
          <Box sx={{ display: 'flex', gap: 2 }}>
            <Button
              startIcon={<Refresh />}
              onClick={() => {
                fetchDashboardData();
                fetchAnomalies();
                fetchAlerts();
                fetchThreats();
                fetchLogs();
              }}
            >
              {t('common.refresh')}
            </Button>
            <Button
              startIcon={<CheckCircle />}
              onClick={handleVerifyIntegrity}
              variant="outlined"
            >
              {t('siem.verifyIntegrity')}
            </Button>
            <Button
              startIcon={<Download />}
              onClick={() => handleExport('csv')}
              variant="outlined"
            >
              {t('common.export')}
            </Button>
          </Box>
        </Box>

        {/* Threat Score */}
        {dashboardData && (
          <Grid container spacing={3} sx={{ mb: 3 }}>
            <Grid item xs={12} md={3}>
              <Card>
                <CardContent>
                  <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                    <Typography variant="h6" color="text.secondary">
                      {t('siem.threatScore')}
                    </Typography>
                    <Assessment color={getThreatScoreColor(dashboardData.threatScore)} />
                  </Box>
                  <Typography variant="h3" sx={{ mt: 2, color: `${getThreatScoreColor(dashboardData.threatScore)}.main` }}>
                    {dashboardData.threatScore}/100
                  </Typography>
                  <LinearProgress
                    variant="determinate"
                    value={dashboardData.threatScore}
                    color={getThreatScoreColor(dashboardData.threatScore)}
                    sx={{ mt: 2, height: 8, borderRadius: 4 }}
                  />
                </CardContent>
              </Card>
            </Grid>

            {/* Anomaly Stats */}
            {['critical', 'high', 'medium', 'low'].map((severity) => (
              <Grid item xs={12} md={2.25} key={severity}>
                <Card>
                  <CardContent>
                    <Typography variant="subtitle2" color="text.secondary">
                      {t(`siem.${severity}Anomalies`)}
                    </Typography>
                    <Typography variant="h4" color={`${getSeverityColor(severity)}.main`} sx={{ mt: 1 }}>
                      {dashboardData.anomalyStats?.[severity] || 0}
                    </Typography>
                  </CardContent>
                </Card>
              </Grid>
            ))}
          </Grid>
        )}

        {/* Tabs */}
        <Paper sx={{ mb: 3 }}>
          <Tabs value={tabValue} onChange={(e, v) => setTabValue(v)} variant="fullWidth">
            <Tab icon={<Badge badgeContent={alerts.length} color="error"><Warning /></Badge>} label={t('siem.alerts')} />
            <Tab icon={<Badge badgeContent={anomalies.length} color="warning"><BugReport /></Badge>} label={t('siem.anomalies')} />
            <Tab icon={<Security />} label={t('siem.threats')} />
            <Tab icon={<Timeline />} label={t('siem.logs')} />
          </Tabs>
        </Paper>

        {/* Alerts Tab */}
        <TabPanel value={tabValue} index={0}>
          <TableContainer component={Paper}>
            <Table>
              <TableHead>
                <TableRow>
                  <TableCell>{t('siem.severity')}</TableCell>
                  <TableCell>{t('siem.title')}</TableCell>
                  <TableCell>{t('siem.description')}</TableCell>
                  <TableCell>{t('siem.time')}</TableCell>
                  <TableCell>{t('common.actions')}</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {alerts.map((alert) => (
                  <TableRow key={alert.alert_id} hover>
                    <TableCell>
                      <Chip 
                        label={alert.severity.toUpperCase()} 
                        color={getSeverityColor(alert.severity)} 
                        size="small" 
                      />
                    </TableCell>
                    <TableCell>
                      <Typography variant="body2" fontWeight="bold">
                        {alert.title}
                      </Typography>
                    </TableCell>
                    <TableCell>
                      <Typography variant="body2" noWrap sx={{ maxWidth: 400 }}>
                        {alert.description}
                      </Typography>
                    </TableCell>
                    <TableCell>
                      <Typography variant="caption" color="text.secondary">
                        {format(new Date(alert.created_at), 'PPpp')}
                      </Typography>
                    </TableCell>
                    <TableCell>
                      <Tooltip title={t('siem.acknowledge')}>
                        <IconButton
                          size="small"
                          onClick={() => handleAcknowledgeAlert(alert.alert_id)}
                        >
                          <CheckCircleOutline />
                        </IconButton>
                      </Tooltip>
                      <Tooltip title={t('siem.viewDetails')}>
                        <IconButton
                          size="small"
                          onClick={() => {
                            setSelectedItem({ ...alert, type: 'alert' });
                            setDetailsDialog(true);
                          }}
                        >
                          <Visibility />
                        </IconButton>
                      </Tooltip>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </TableContainer>
        </TabPanel>

        {/* Anomalies Tab */}
        <TabPanel value={tabValue} index={1}>
          <TableContainer component={Paper}>
            <Table>
              <TableHead>
                <TableRow>
                  <TableCell>{t('siem.severity')}</TableCell>
                  <TableCell>{t('siem.type')}</TableCell>
                  <TableCell>{t('siem.description')}</TableCell>
                  <TableCell>{t('siem.confidence')}</TableCell>
                  <TableCell>{t('siem.time')}</TableCell>
                  <TableCell>{t('common.actions')}</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {anomalies.map((anomaly) => (
                  <TableRow key={anomaly.anomaly_id} hover>
                    <TableCell>
                      <Chip 
                        label={anomaly.severity.toUpperCase()} 
                        color={getSeverityColor(anomaly.severity)} 
                        size="small" 
                      />
                    </TableCell>
                    <TableCell>
                      <Chip label={anomaly.type.replace(/_/g, ' ')} variant="outlined" size="small" />
                    </TableCell>
                    <TableCell>
                      <Typography variant="body2" noWrap sx={{ maxWidth: 400 }}>
                        {anomaly.description}
                      </Typography>
                    </TableCell>
                    <TableCell>
                      <Typography variant="body2" color="text.secondary">
                        {(anomaly.confidence * 100).toFixed(0)}%
                      </Typography>
                    </TableCell>
                    <TableCell>
                      <Typography variant="caption" color="text.secondary">
                        {format(new Date(anomaly.created_at), 'PPpp')}
                      </Typography>
                    </TableCell>
                    <TableCell>
                      <Tooltip title={t('siem.viewDetails')}>
                        <IconButton
                          size="small"
                          onClick={() => {
                            setSelectedItem({ ...anomaly, type: 'anomaly' });
                            setDetailsDialog(true);
                          }}
                        >
                          <Visibility />
                        </IconButton>
                      </Tooltip>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </TableContainer>
        </TabPanel>

        {/* Threats Tab */}
        <TabPanel value={tabValue} index={2}>
          <TableContainer component={Paper}>
            <Table>
              <TableHead>
                <TableRow>
                  <TableCell>{t('siem.threatLevel')}</TableCell>
                  <TableCell>{t('siem.indicator')}</TableCell>
                  <TableCell>{t('siem.type')}</TableCell>
                  <TableCell>{t('siem.description')}</TableCell>
                  <TableCell>{t('siem.occurrences')}</TableCell>
                  <TableCell>{t('siem.lastSeen')}</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {threats.map((threat) => (
                  <TableRow key={threat.id} hover>
                    <TableCell>
                      <Chip 
                        label={threat.threat_level.toUpperCase()} 
                        color={getSeverityColor(threat.threat_level)} 
                        size="small" 
                      />
                    </TableCell>
                    <TableCell>
                      <Typography variant="body2" fontWeight="bold">
                        {threat.indicator}
                      </Typography>
                    </TableCell>
                    <TableCell>
                      <Chip label={threat.indicator_type.toUpperCase()} variant="outlined" size="small" />
                    </TableCell>
                    <TableCell>
                      <Typography variant="body2" noWrap sx={{ maxWidth: 300 }}>
                        {threat.description}
                      </Typography>
                    </TableCell>
                    <TableCell>
                      <Typography variant="body2" color="text.secondary">
                        {threat.occurrence_count}
                      </Typography>
                    </TableCell>
                    <TableCell>
                      <Typography variant="caption" color="text.secondary">
                        {format(new Date(threat.last_seen), 'PPpp')}
                      </Typography>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </TableContainer>
        </TabPanel>

        {/* Logs Tab */}
        <TabPanel value={tabValue} index={3}>
          <TableContainer component={Paper}>
            <Table size="small">
              <TableHead>
                <TableRow>
                  <TableCell>{t('siem.level')}</TableCell>
                  <TableCell>{t('siem.source')}</TableCell>
                  <TableCell>{t('siem.category')}</TableCell>
                  <TableCell>{t('siem.message')}</TableCell>
                  <TableCell>{t('siem.time')}</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {logs.map((log) => (
                  <TableRow key={log.log_id} hover>
                    <TableCell>
                      <Chip 
                        label={log.level.toUpperCase()} 
                        color={getSeverityColor(log.level === 'error' ? 'high' : log.level === 'warn' ? 'medium' : 'low')} 
                        size="small" 
                      />
                    </TableCell>
                    <TableCell>
                      <Chip label={log.source} variant="outlined" size="small" />
                    </TableCell>
                    <TableCell>
                      <Typography variant="caption">{log.category}</Typography>
                    </TableCell>
                    <TableCell>
                      <Typography variant="body2" noWrap sx={{ maxWidth: 500 }}>
                        {log.message}
                      </Typography>
                    </TableCell>
                    <TableCell>
                      <Typography variant="caption" color="text.secondary">
                        {format(new Date(log.timestamp), 'PPpp')}
                      </Typography>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </TableContainer>
        </TabPanel>

        {/* Details Dialog */}
        <Dialog open={detailsDialog} onClose={() => setDetailsDialog(false)} maxWidth="md" fullWidth>
          {selectedItem && (
            <>
              <DialogTitle>
                {selectedItem.type === 'alert' ? t('siem.alertDetails') : t('siem.anomalyDetails')}
              </DialogTitle>
              <DialogContent dividers>
                <List>
                  <ListItem>
                    <ListItemText
                      primary={t('siem.severity')}
                      secondary={
                        <Chip 
                          label={selectedItem.severity.toUpperCase()} 
                          color={getSeverityColor(selectedItem.severity)} 
                          size="small" 
                        />
                      }
                    />
                  </ListItem>
                  <Divider />
                  <ListItem>
                    <ListItemText
                      primary={selectedItem.type === 'alert' ? t('siem.title') : t('siem.type')}
                      secondary={selectedItem.title || selectedItem.type}
                    />
                  </ListItem>
                  <Divider />
                  <ListItem>
                    <ListItemText
                      primary={t('siem.description')}
                      secondary={selectedItem.description}
                    />
                  </ListItem>
                  {selectedItem.confidence && (
                    <>
                      <Divider />
                      <ListItem>
                        <ListItemText
                          primary={t('siem.confidence')}
                          secondary={`${(selectedItem.confidence * 100).toFixed(0)}%`}
                        />
                      </ListItem>
                    </>
                  )}
                  <Divider />
                  <ListItem>
                    <ListItemText
                      primary={t('siem.time')}
                      secondary={format(new Date(selectedItem.created_at), 'PPPppp')}
                    />
                  </ListItem>
                </List>
                <TextField
                  fullWidth
                  multiline
                  rows={3}
                  label={t('siem.resolutionNotes')}
                  placeholder={t('siem.resolutionNotesPlaceholder')}
                  sx={{ mt: 2 }}
                  id="resolution-notes"
                />
              </DialogContent>
              <DialogActions>
                <Button onClick={() => setDetailsDialog(false)}>
                  {t('common.cancel')}
                </Button>
                <Button
                  onClick={() => {
                    const notes = document.getElementById('resolution-notes').value;
                    if (selectedItem.type === 'alert') {
                      handleResolveAlert(selectedItem.alert_id, notes);
                    } else {
                      handleResolveAnomaly(selectedItem.anomaly_id, notes);
                    }
                  }}
                  variant="contained"
                  color="primary"
                >
                  {t('siem.resolve')}
                </Button>
              </DialogActions>
            </>
          )}
        </Dialog>
      </Box>
    </Container>
  );
};

export default SecurityIntelligenceDashboard;
