import React, { useState, useEffect } from 'react';
import {
  Box,
  Container,
  Typography,
  Card,
  CardContent,
  Grid,
  Button,
  IconButton,
  Tabs,
  Tab,
  Alert,
  CircularProgress,
  Chip,
  LinearProgress,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  Accordion,
  AccordionSummary,
  AccordionDetails,
  FormGroup,
  FormControlLabel,
  Checkbox,
  Divider,
  List,
  ListItem,
  ListItemText,
  ListItemIcon
} from '@mui/material';
import {
  Security,
  PlayArrow,
  Refresh,
  ArrowBack,
  CheckCircle,
  Error as ErrorIcon,
  Warning,
  Shield,
  ExpandMore,
  BugReport,
  Lock,
  VpnLock,
  Storage,
  Code,
  NetworkCheck
} from '@mui/icons-material';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
import api from '../utils/api';

function TabPanel({ children, value, index }) {
  return value === index ? <Box sx={{ pt: 3 }}>{children}</Box> : null;
}

const SecurityTestingDashboard = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  const [tabValue, setTabValue] = useState(0);
  
  // Data states
  const [defenseLayers, setDefenseLayers] = useState(null);
  const [testResults, setTestResults] = useState(null);
  const [testHistory, setTestHistory] = useState([]);
  const [networkStats, setNetworkStats] = useState(null);
  const [testing, setTesting] = useState(false);
  
  // Test selection
  const [selectedTests, setSelectedTests] = useState({
    auth: true,
    sql: true,
    xss: true,
    csrf: true,
    rate: true
  });

  useEffect(() => {
    fetchDefenseLayers();
    fetchTestHistory();
    fetchNetworkStats();
  }, []);

  const fetchDefenseLayers = async () => {
    try {
      const response = await api.get('/security-testing/defense-layers');
      setDefenseLayers(response.data);
    } catch (err) {
      console.error('Error fetching defense layers:', err);
    }
  };

  const fetchTestHistory = async () => {
    try {
      const response = await api.get('/security-testing/test-history?limit=20');
      setTestHistory(response.data);
    } catch (err) {
      console.error('Error fetching test history:', err);
    }
  };

  const fetchNetworkStats = async () => {
    try {
      const response = await api.get('/security-testing/network-stats');
      setNetworkStats(response.data);
    } catch (err) {
      console.error('Error fetching network stats:', err);
    }
  };

  const handleRunPenetrationTests = async () => {
    setTesting(true);
    setError('');
    setSuccess('');
    
    try {
      const testTypes = Object.keys(selectedTests).filter(key => selectedTests[key]);
      
      const response = await api.post('/security-testing/penetration-test', {
        testTypes: testTypes.length === 5 ? ['all'] : testTypes
      });
      
      setTestResults(response.data);
      setSuccess(t('security.testsCompleted'));
      fetchTestHistory();
    } catch (err) {
      setError(t('security.testsFailed'));
      console.error('Error running penetration tests:', err);
    } finally {
      setTesting(false);
    }
  };

  const getLayerIcon = (layer) => {
    switch (layer) {
      case 'Network Level': return <NetworkCheck />;
      case 'Server Level': return <Shield />;
      case 'Application Level': return <Code />;
      case 'Data Level': return <Storage />;
      default: return <Security />;
    }
  };

  const getScoreColor = (score) => {
    if (score >= 90) return 'success';
    if (score >= 75) return 'warning';
    return 'error';
  };

  const getStatusIcon = (status) => {
    switch (status) {
      case 'pass': return <CheckCircle color="success" />;
      case 'fail': return <ErrorIcon color="error" />;
      case 'warn': return <Warning color="warning" />;
      default: return <Warning color="info" />;
    }
  };

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

  if (loading) {
    return (
      <Container maxWidth="xl" sx={{ mt: 4, mb: 4 }}>
        <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', minHeight: 400 }}>
          <CircularProgress />
        </Box>
      </Container>
    );
  }

  return (
    <Container maxWidth="xl" sx={{ mt: 4, mb: 4 }}>
      {/* Header */}
      <Box sx={{ mb: 3, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
          <IconButton onClick={() => navigate('/security')} size="small">
            <ArrowBack />
          </IconButton>
          <BugReport sx={{ fontSize: 40, color: 'primary.main' }} />
          <Box>
            <Typography variant="h4" fontWeight="bold">
              {t('security.securityTesting')}
            </Typography>
            <Typography variant="body2" color="text.secondary">
              {t('security.automatedAndManualTesting')}
            </Typography>
          </Box>
        </Box>
        <Box sx={{ display: 'flex', gap: 1 }}>
          <Button
            startIcon={<Refresh />}
            onClick={() => {
              fetchDefenseLayers();
              fetchTestHistory();
              fetchNetworkStats();
            }}
            variant="outlined"
          >
            {t('common.refresh')}
          </Button>
        </Box>
      </Box>

      {/* Alerts */}
      {error && (
        <Alert severity="error" onClose={() => setError('')} sx={{ mb: 2 }}>
          {error}
        </Alert>
      )}
      {success && (
        <Alert severity="success" onClose={() => setSuccess('')} sx={{ mb: 2 }}>
          {success}
        </Alert>
      )}

      {/* Overall Security Score */}
      {defenseLayers && (
        <Card sx={{ mb: 3, background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)' }}>
          <CardContent>
            <Grid container spacing={3} alignItems="center">
              <Grid item xs={12} md={3}>
                <Box sx={{ textAlign: 'center', color: 'white' }}>
                  <Typography variant="h2" fontWeight="bold">
                    {defenseLayers.overall_score}
                  </Typography>
                  <Typography variant="h6">
                    {t('security.overallScore')}
                  </Typography>
                  <Chip 
                    label={defenseLayers.overall_score >= 90 ? 'A' : defenseLayers.overall_score >= 80 ? 'B' : defenseLayers.overall_score >= 70 ? 'C' : 'D'}
                    sx={{ mt: 1, bgcolor: 'white', color: 'primary.main', fontWeight: 'bold' }}
                  />
                </Box>
              </Grid>
              <Grid item xs={12} md={9}>
                <Box sx={{ color: 'white' }}>
                  <Typography variant="h6" gutterBottom>
                    {t('security.defenseInDepth')}
                  </Typography>
                  <Grid container spacing={2}>
                    {[defenseLayers.network, defenseLayers.server, defenseLayers.application, defenseLayers.data].map((layer, index) => (
                      <Grid item xs={12} sm={6} md={3} key={index}>
                        <Box>
                          <Typography variant="body2" gutterBottom>
                            {layer.layer}
                          </Typography>
                          <LinearProgress 
                            variant="determinate" 
                            value={layer.score} 
                            sx={{ 
                              height: 8, 
                              borderRadius: 1,
                              bgcolor: 'rgba(255,255,255,0.2)',
                              '& .MuiLinearProgress-bar': {
                                bgcolor: layer.score >= 80 ? 'success.light' : layer.score >= 60 ? 'warning.light' : 'error.light'
                              }
                            }} 
                          />
                          <Typography variant="caption">
                            {layer.score}/100
                          </Typography>
                        </Box>
                      </Grid>
                    ))}
                  </Grid>
                </Box>
              </Grid>
            </Grid>
          </CardContent>
        </Card>
      )}

      {/* Tabs */}
      <Card>
        <Tabs value={tabValue} onChange={(e, v) => setTabValue(v)} sx={{ borderBottom: 1, borderColor: 'divider' }}>
          <Tab label={t('security.defenseInDepth')} />
          <Tab label={t('security.penetrationTesting')} />
          <Tab label={t('security.testHistory')} />
          <Tab label={t('security.networkSecurity')} />
        </Tabs>

        {/* Defense-in-Depth Tab */}
        <TabPanel value={tabValue} index={0}>
          <CardContent>
            {defenseLayers && (
              <Grid container spacing={3}>
                {[defenseLayers.network, defenseLayers.server, defenseLayers.application, defenseLayers.data].map((layer, layerIndex) => (
                  <Grid item xs={12} key={layerIndex}>
                    <Card variant="outlined">
                      <CardContent>
                        <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', mb: 2 }}>
                          <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
                            {getLayerIcon(layer.layer)}
                            <Box>
                              <Typography variant="h6" fontWeight="medium">
                                {layer.layer}
                              </Typography>
                              <Typography variant="caption" color="text.secondary">
                                {layer.checks.length} {t('security.checks')}
                              </Typography>
                            </Box>
                          </Box>
                          <Box sx={{ textAlign: 'right' }}>
                            <Typography variant="h4" color={getScoreColor(layer.score) + '.main'} fontWeight="bold">
                              {layer.score}
                            </Typography>
                            <Typography variant="caption" color="text.secondary">
                              {t('security.score')}
                            </Typography>
                          </Box>
                        </Box>

                        <Divider sx={{ my: 2 }} />

                        {/* Checks */}
                        <List>
                          {layer.checks.map((check, checkIndex) => (
                            <ListItem key={checkIndex}>
                              <ListItemIcon>
                                {getStatusIcon(check.status)}
                              </ListItemIcon>
                              <ListItemText
                                primary={check.name}
                                secondary={check.details}
                              />
                            </ListItem>
                          ))}
                        </List>

                        {/* Recommendations */}
                        {layer.recommendations.length > 0 && (
                          <>
                            <Divider sx={{ my: 2 }} />
                            <Typography variant="subtitle2" color="warning.main" gutterBottom>
                              {t('security.recommendations')}:
                            </Typography>
                            {layer.recommendations.map((rec, recIndex) => (
                              <Alert key={recIndex} severity="warning" sx={{ mb: 1 }}>
                                {rec}
                              </Alert>
                            ))}
                          </>
                        )}
                      </CardContent>
                    </Card>
                  </Grid>
                ))}
              </Grid>
            )}
          </CardContent>
        </TabPanel>

        {/* Penetration Testing Tab */}
        <TabPanel value={tabValue} index={1}>
          <CardContent>
            <Alert severity="info" sx={{ mb: 3 }}>
              {t('security.penetrationTestingInfo')}
            </Alert>

            <Typography variant="h6" gutterBottom>
              {t('security.selectTests')}
            </Typography>
            <FormGroup row>
              <FormControlLabel
                control={<Checkbox checked={selectedTests.auth} onChange={(e) => setSelectedTests({...selectedTests, auth: e.target.checked})} />}
                label={t('security.authenticationTests')}
              />
              <FormControlLabel
                control={<Checkbox checked={selectedTests.sql} onChange={(e) => setSelectedTests({...selectedTests, sql: e.target.checked})} />}
                label={t('security.sqlInjectionTests')}
              />
              <FormControlLabel
                control={<Checkbox checked={selectedTests.xss} onChange={(e) => setSelectedTests({...selectedTests, xss: e.target.checked})} />}
                label={t('security.xssTests')}
              />
              <FormControlLabel
                control={<Checkbox checked={selectedTests.csrf} onChange={(e) => setSelectedTests({...selectedTests, csrf: e.target.checked})} />}
                label={t('security.csrfTests')}
              />
              <FormControlLabel
                control={<Checkbox checked={selectedTests.rate} onChange={(e) => setSelectedTests({...selectedTests, rate: e.target.checked})} />}
                label={t('security.rateLimitTests')}
              />
            </FormGroup>

            <Box sx={{ mt: 3 }}>
              <Button
                variant="contained"
                color="primary"
                size="large"
                startIcon={testing ? <CircularProgress size={20} color="inherit" /> : <PlayArrow />}
                onClick={handleRunPenetrationTests}
                disabled={testing || Object.values(selectedTests).every(v => !v)}
              >
                {testing ? t('security.runningTests') : t('security.runPenetrationTests')}
              </Button>
            </Box>

            {testResults && (
              <Box sx={{ mt: 4 }}>
                <Typography variant="h6" gutterBottom>
                  {t('security.testResults')}
                </Typography>
                
                <Grid container spacing={2} sx={{ mb: 3 }}>
                  <Grid item xs={4}>
                    <Card>
                      <CardContent>
                        <Typography variant="h3" color="success.main" fontWeight="bold">
                          {testResults.summary.passed}
                        </Typography>
                        <Typography variant="body2" color="text.secondary">
                          {t('security.passed')}
                        </Typography>
                      </CardContent>
                    </Card>
                  </Grid>
                  <Grid item xs={4}>
                    <Card>
                      <CardContent>
                        <Typography variant="h3" color="error.main" fontWeight="bold">
                          {testResults.summary.failed}
                        </Typography>
                        <Typography variant="body2" color="text.secondary">
                          {t('security.failed')}
                        </Typography>
                      </CardContent>
                    </Card>
                  </Grid>
                  <Grid item xs={4}>
                    <Card>
                      <CardContent>
                        <Typography variant="h3" color="warning.main" fontWeight="bold">
                          {testResults.summary.warnings}
                        </Typography>
                        <Typography variant="body2" color="text.secondary">
                          {t('security.warnings')}
                        </Typography>
                      </CardContent>
                    </Card>
                  </Grid>
                </Grid>

                {testResults.tests.map((test, index) => (
                  <Accordion key={index}>
                    <AccordionSummary expandIcon={<ExpandMore />}>
                      <Box sx={{ display: 'flex', alignItems: 'center', gap: 2, width: '100%' }}>
                        {test.passed ? <CheckCircle color="success" /> : <ErrorIcon color="error" />}
                        <Typography variant="subtitle1" fontWeight="medium">
                          {test.name}
                        </Typography>
                        <Chip 
                          label={test.severity.toUpperCase()} 
                          size="small" 
                          color={getSeverityColor(test.severity)}
                        />
                        <Typography variant="caption" color="text.secondary" sx={{ ml: 'auto' }}>
                          {test.duration_ms}ms
                        </Typography>
                      </Box>
                    </AccordionSummary>
                    <AccordionDetails>
                      <Typography variant="body2" color="text.secondary" gutterBottom>
                        <strong>{t('security.findings')}:</strong>
                      </Typography>
                      <List dense>
                        {test.findings.map((finding, fIndex) => (
                          <ListItem key={fIndex}>
                            <ListItemText primary={finding} />
                          </ListItem>
                        ))}
                      </List>
                      {test.recommendations.length > 0 && (
                        <>
                          <Typography variant="body2" color="text.secondary" gutterBottom sx={{ mt: 2 }}>
                            <strong>{t('security.recommendations')}:</strong>
                          </Typography>
                          <List dense>
                            {test.recommendations.map((rec, rIndex) => (
                              <ListItem key={rIndex}>
                                <ListItemText primary={rec} />
                              </ListItem>
                            ))}
                          </List>
                        </>
                      )}
                    </AccordionDetails>
                  </Accordion>
                ))}
              </Box>
            )}
          </CardContent>
        </TabPanel>

        {/* Test History Tab */}
        <TabPanel value={tabValue} index={2}>
          <CardContent>
            {testHistory.length === 0 ? (
              <Alert severity="info">{t('security.noTestHistory')}</Alert>
            ) : (
              <TableContainer>
                <Table>
                  <TableHead>
                    <TableRow>
                      <TableCell>{t('security.timestamp')}</TableCell>
                      <TableCell>{t('security.testType')}</TableCell>
                      <TableCell>{t('security.testName')}</TableCell>
                      <TableCell>{t('security.status')}</TableCell>
                      <TableCell>{t('security.severity')}</TableCell>
                      <TableCell>{t('security.executedBy')}</TableCell>
                      <TableCell>{t('security.duration')}</TableCell>
                    </TableRow>
                  </TableHead>
                  <TableBody>
                    {testHistory.map((test) => (
                      <TableRow key={test.id}>
                        <TableCell>{new Date(test.started_at).toLocaleString()}</TableCell>
                        <TableCell>
                          <Chip label={test.test_type} size="small" />
                        </TableCell>
                        <TableCell>{test.test_name}</TableCell>
                        <TableCell>
                          <Chip 
                            label={test.status} 
                            size="small" 
                            color={test.status === 'pass' ? 'success' : 'error'}
                          />
                        </TableCell>
                        <TableCell>
                          <Chip 
                            label={test.severity} 
                            size="small" 
                            color={getSeverityColor(test.severity)}
                          />
                        </TableCell>
                        <TableCell>{test.username || '-'}</TableCell>
                        <TableCell>{test.duration_ms}ms</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </TableContainer>
            )}
          </CardContent>
        </TabPanel>

        {/* Network Security Tab */}
        <TabPanel value={tabValue} index={3}>
          <CardContent>
            {networkStats && (
              <Grid container spacing={3}>
                <Grid item xs={12} md={4}>
                  <Card>
                    <CardContent>
                      <Typography variant="h4" fontWeight="bold" color="primary">
                        {networkStats.active_connections.count}
                      </Typography>
                      <Typography variant="body2" color="text.secondary">
                        {t('security.activeConnections')}
                      </Typography>
                    </CardContent>
                  </Card>
                </Grid>
                <Grid item xs={12} md={4}>
                  <Card>
                    <CardContent>
                      <Typography variant="h4" fontWeight="bold" color="error">
                        {networkStats.blocked_requests.count}
                      </Typography>
                      <Typography variant="body2" color="text.secondary">
                        {t('security.blockedRequests')} (24h)
                      </Typography>
                    </CardContent>
                  </Card>
                </Grid>
                <Grid item xs={12} md={4}>
                  <Card>
                    <CardContent>
                      <Typography variant="h4" fontWeight="bold" color="warning">
                        {networkStats.rate_limiting.failed_logins}
                      </Typography>
                      <Typography variant="body2" color="text.secondary">
                        {t('security.failedLogins')} (24h)
                      </Typography>
                    </CardContent>
                  </Card>
                </Grid>

                <Grid item xs={12}>
                  <Card variant="outlined">
                    <CardContent>
                      <Typography variant="h6" gutterBottom>
                        {t('security.rateLimitingStats')}
                      </Typography>
                      <Grid container spacing={2}>
                        <Grid item xs={12} sm={6}>
                          <Typography variant="body2" color="text.secondary">
                            {t('security.totalRequests')} (24h)
                          </Typography>
                          <Typography variant="h5">
                            {networkStats.rate_limiting.total_requests}
                          </Typography>
                        </Grid>
                        <Grid item xs={12} sm={6}>
                          <Typography variant="body2" color="text.secondary">
                            {t('security.rateLimited')} (24h)
                          </Typography>
                          <Typography variant="h5" color="warning.main">
                            {networkStats.rate_limiting.rate_limited}
                          </Typography>
                        </Grid>
                      </Grid>
                    </CardContent>
                  </Card>
                </Grid>
              </Grid>
            )}
          </CardContent>
        </TabPanel>
      </Card>
    </Container>
  );
};

export default SecurityTestingDashboard;
