import React, { useState, useEffect } from 'react';
import {
  Box,
  Container,
  Typography,
  Card,
  CardContent,
  Grid,
  Button,
  IconButton,
  Tabs,
  Tab,
  Alert,
  CircularProgress,
  Chip,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
  Select,
  MenuItem,
  FormControl,
  InputLabel,
  FormControlLabel,
  Switch,
  Accordion,
  AccordionSummary,
  AccordionDetails,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  Divider,
  List,
  ListItem,
  ListItemText,
  ListItemIcon,
  LinearProgress
} from '@mui/material';
import {
  Security,
  Refresh,
  Save,
  PlayArrow,
  ArrowBack,
  Add,
  Delete,
  CheckCircle,
  Warning,
  Error as ErrorIcon,
  Info,
  ExpandMore,
  ContentCopy,
  History,
  Settings
} 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 SecurityHeadersDashboard = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  const [tabValue, setTabValue] = useState(0);
  
  // Data states
  const [currentConfig, setCurrentConfig] = useState(null);
  const [savedConfigs, setSavedConfigs] = useState([]);
  const [presets, setPresets] = useState({});
  const [recommendations, setRecommendations] = useState(null);
  const [testResults, setTestResults] = useState(null);
  const [history, setHistory] = useState([]);

  // Dialog states
  const [saveDialogOpen, setSaveDialogOpen] = useState(false);
  const [testDialogOpen, setTestDialogOpen] = useState(false);
  const [presetDialogOpen, setPresetDialogOpen] = useState(false);
  
  // Form states
  const [configName, setConfigName] = useState('');
  const [selectedPreset, setSelectedPreset] = useState('');
  const [editableConfig, setEditableConfig] = useState(null);

  useEffect(() => {
    fetchData();
    fetchRecommendations();
  }, []);

  const fetchData = async () => {
    setLoading(true);
    setError('');
    try {
      const response = await api.get('/security-headers/current');
      setCurrentConfig(response.data.current);
      setSavedConfigs(response.data.savedConfigs);
      setPresets(response.data.presets);
      
      // Initialize editable config with current config
      if (response.data.current && !editableConfig) {
        setEditableConfig(convertToEditableFormat(response.data.current));
      }
    } catch (err) {
      setError(t('security.failedToLoad'));
      console.error('Error fetching security headers:', err);
    } finally {
      setLoading(false);
    }
  };

  const fetchRecommendations = async () => {
    try {
      const response = await api.get('/security-headers/recommendations');
      setRecommendations(response.data);
    } catch (err) {
      console.error('Error fetching recommendations:', err);
    }
  };

  const fetchHistory = async () => {
    try {
      const response = await api.get('/security-headers/history');
      setHistory(response.data);
    } catch (err) {
      console.error('Error fetching history:', err);
    }
  };

  const handleTestConfiguration = async () => {
    if (!editableConfig) return;
    
    setTestDialogOpen(true);
    try {
      const response = await api.post('/security-headers/test', {
        config: editableConfig
      });
      setTestResults(response.data);
    } catch (err) {
      setError(t('security.testFailed'));
      console.error('Error testing configuration:', err);
    }
  };

  const handleSaveConfiguration = async () => {
    if (!configName || !editableConfig) {
      setError(t('security.nameRequired'));
      return;
    }

    try {
      await api.post('/security-headers/save', {
        configName,
        config: editableConfig,
        setActive: false
      });
      
      setSuccess(t('security.configSaved'));
      setSaveDialogOpen(false);
      setConfigName('');
      fetchData();
    } catch (err) {
      setError(t('security.saveFailed'));
      console.error('Error saving configuration:', err);
    }
  };

  const handleApplyConfiguration = async (configId) => {
    if (!window.confirm(t('security.confirmApply'))) return;

    try {
      const response = await api.post(`/security-headers/apply/${configId}`);
      
      if (response.data.requiresRestart) {
        setSuccess(t('security.configAppliedRestart'));
      } else {
        setSuccess(t('security.configApplied'));
      }
      
      fetchData();
    } catch (err) {
      setError(t('security.applyFailed'));
      console.error('Error applying configuration:', err);
    }
  };

  const handleDeleteConfiguration = async (configId) => {
    if (!window.confirm(t('security.confirmDelete'))) return;

    try {
      await api.delete(`/security-headers/${configId}`);
      setSuccess(t('security.configDeleted'));
      fetchData();
    } catch (err) {
      setError(t('security.deleteFailed'));
      console.error('Error deleting configuration:', err);
    }
  };

  const handleApplyPreset = () => {
    if (!selectedPreset || !presets[selectedPreset]) return;
    
    setEditableConfig(presets[selectedPreset].config);
    setPresetDialogOpen(false);
    setSuccess(t('security.presetApplied', { preset: presets[selectedPreset].name }));
  };

  const convertToEditableFormat = (config) => {
    return {
      csp_default_src: JSON.stringify(config.csp?.directives?.defaultSrc || ["'self'"]),
      csp_script_src: JSON.stringify(config.csp?.directives?.scriptSrc || ["'self'"]),
      csp_style_src: JSON.stringify(config.csp?.directives?.styleSrc || ["'self'"]),
      csp_img_src: JSON.stringify(config.csp?.directives?.imgSrc || ["'self'"]),
      csp_media_src: JSON.stringify(config.csp?.directives?.mediaSrc || ["'self'"]),
      csp_connect_src: JSON.stringify(config.csp?.directives?.connectSrc || ["'self'"]),
      csp_font_src: JSON.stringify(config.csp?.directives?.fontSrc || ["'self'"]),
      csp_frame_src: JSON.stringify(config.csp?.directives?.frameSrc || ["'self'"]),
      csp_object_src: JSON.stringify(config.csp?.directives?.objectSrc || ["'none'"]),
      csp_base_uri: JSON.stringify(config.csp?.directives?.baseUri || ["'self'"]),
      csp_form_action: JSON.stringify(config.csp?.directives?.formAction || ["'self'"]),
      csp_frame_ancestors: JSON.stringify(config.csp?.directives?.frameAncestors || ["'self'"]),
      hsts_enabled: config.hsts?.enabled !== false,
      hsts_max_age: config.hsts?.maxAge || 31536000,
      hsts_include_subdomains: config.hsts?.includeSubDomains !== false,
      hsts_preload: config.hsts?.preload !== false,
      referrer_policy: config.referrerPolicy || 'strict-origin-when-cross-origin',
      x_content_type_options: config.xContentTypeOptions !== false,
      x_frame_options: config.xFrameOptions || 'SAMEORIGIN',
      x_xss_protection: config.xssProtection !== false
    };
  };

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

  const getSeverityIcon = (severity) => {
    switch (severity) {
      case 'error': return <ErrorIcon />;
      case 'warning': return <Warning />;
      case 'info': return <Info />;
      default: return <CheckCircle />;
    }
  };

  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>
          <Security sx={{ fontSize: 40, color: 'primary.main' }} />
          <Box>
            <Typography variant="h4" fontWeight="bold">
              {t('security.securityHeaders')}
            </Typography>
            <Typography variant="body2" color="text.secondary">
              {t('security.manageHttpHeaders')}
            </Typography>
          </Box>
        </Box>
        <Box sx={{ display: 'flex', gap: 1 }}>
          <Button
            startIcon={<Refresh />}
            onClick={fetchData}
            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>
      )}

      {/* Security Score Card */}
      {recommendations && (
        <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">
                    {recommendations.score}
                  </Typography>
                  <Typography variant="h6">
                    {t('security.securityScore')}
                  </Typography>
                  <Chip 
                    label={`${t('security.grade')}: ${recommendations.grade}`}
                    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.securitySummary')}
                  </Typography>
                  <Grid container spacing={2}>
                    <Grid item xs={4}>
                      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                        <ErrorIcon />
                        <Typography>
                          {recommendations.summary.critical} {t('security.critical')}
                        </Typography>
                      </Box>
                    </Grid>
                    <Grid item xs={4}>
                      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                        <Warning />
                        <Typography>
                          {recommendations.summary.warnings} {t('security.warnings')}
                        </Typography>
                      </Box>
                    </Grid>
                    <Grid item xs={4}>
                      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                        <Info />
                        <Typography>
                          {recommendations.summary.info} {t('security.info')}
                        </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.currentConfig')} />
          <Tab label={t('security.editor')} />
          <Tab label={t('security.savedConfigs')} />
          <Tab label={t('security.recommendations')} />
          <Tab label={t('security.history')} onClick={() => tabValue === 4 && fetchHistory()} />
        </Tabs>

        {/* Current Configuration Tab */}
        <TabPanel value={tabValue} index={0}>
          <CardContent>
            <Alert severity="info" sx={{ mb: 3 }}>
              {t('security.currentConfigDescription')}
            </Alert>
            
            {currentConfig && (
              <>
                <Typography variant="h6" gutterBottom>
                  {t('security.environment')}: {currentConfig.environment}
                </Typography>
                <Typography variant="body2" color="text.secondary" gutterBottom>
                  CSP {t('security.mode')}: {currentConfig.csp.mode}
                </Typography>

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

                <Typography variant="h6" gutterBottom>
                  {t('security.contentSecurityPolicy')}
                </Typography>
                {currentConfig.csp.directives && Object.entries(currentConfig.csp.directives).map(([key, value]) => (
                  <Accordion key={key}>
                    <AccordionSummary expandIcon={<ExpandMore />}>
                      <Typography fontWeight="medium">{key}</Typography>
                    </AccordionSummary>
                    <AccordionDetails>
                      <Box sx={{ bgcolor: 'grey.100', p: 2, borderRadius: 1, fontFamily: 'monospace' }}>
                        {JSON.stringify(value, null, 2)}
                      </Box>
                    </AccordionDetails>
                  </Accordion>
                ))}

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

                <Typography variant="h6" gutterBottom>
                  {t('security.otherHeaders')}
                </Typography>
                <Grid container spacing={2}>
                  <Grid item xs={12} md={6}>
                    <Card variant="outlined">
                      <CardContent>
                        <Typography variant="subtitle2" color="text.secondary">
                          HSTS
                        </Typography>
                        <Typography>
                          {currentConfig.hsts.enabled ? t('common.enabled') : t('common.disabled')}
                          {currentConfig.hsts.enabled && ` (${currentConfig.hsts.maxAge}s)`}
                        </Typography>
                      </CardContent>
                    </Card>
                  </Grid>
                  <Grid item xs={12} md={6}>
                    <Card variant="outlined">
                      <CardContent>
                        <Typography variant="subtitle2" color="text.secondary">
                          Referrer-Policy
                        </Typography>
                        <Typography>{currentConfig.referrerPolicy}</Typography>
                      </CardContent>
                    </Card>
                  </Grid>
                  <Grid item xs={12} md={6}>
                    <Card variant="outlined">
                      <CardContent>
                        <Typography variant="subtitle2" color="text.secondary">
                          X-Content-Type-Options
                        </Typography>
                        <Typography>
                          {currentConfig.xContentTypeOptions ? 'nosniff' : t('common.disabled')}
                        </Typography>
                      </CardContent>
                    </Card>
                  </Grid>
                  <Grid item xs={12} md={6}>
                    <Card variant="outlined">
                      <CardContent>
                        <Typography variant="subtitle2" color="text.secondary">
                          X-Frame-Options
                        </Typography>
                        <Typography>{currentConfig.xFrameOptions}</Typography>
                      </CardContent>
                    </Card>
                  </Grid>
                </Grid>
              </>
            )}
          </CardContent>
        </TabPanel>

        {/* Editor Tab */}
        <TabPanel value={tabValue} index={1}>
          <CardContent>
            <Box sx={{ mb: 3, display: 'flex', gap: 1, flexWrap: 'wrap' }}>
              <Button
                startIcon={<Settings />}
                onClick={() => setPresetDialogOpen(true)}
                variant="outlined"
              >
                {t('security.loadPreset')}
              </Button>
              <Button
                startIcon={<PlayArrow />}
                onClick={handleTestConfiguration}
                variant="outlined"
                color="primary"
              >
                {t('security.testConfig')}
              </Button>
              <Button
                startIcon={<Save />}
                onClick={() => setSaveDialogOpen(true)}
                variant="contained"
              >
                {t('security.saveConfig')}
              </Button>
            </Box>

            <Alert severity="warning" sx={{ mb: 3 }}>
              {t('security.editorWarning')}
            </Alert>

            {editableConfig && (
              <Box>
                <Typography variant="h6" gutterBottom>
                  {t('security.cspDirectives')}
                </Typography>
                <Grid container spacing={2}>
                  {Object.entries(editableConfig).filter(([key]) => key.startsWith('csp_')).map(([key, value]) => (
                    <Grid item xs={12} key={key}>
                      <TextField
                        fullWidth
                        label={key.replace('csp_', '').replace(/_/g, '-')}
                        value={value}
                        onChange={(e) => setEditableConfig({ ...editableConfig, [key]: e.target.value })}
                        multiline
                        rows={2}
                        helperText={t('security.jsonArrayFormat')}
                      />
                    </Grid>
                  ))}
                </Grid>

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

                <Typography variant="h6" gutterBottom>
                  {t('security.hstsConfiguration')}
                </Typography>
                <Grid container spacing={2}>
                  <Grid item xs={12}>
                    <FormControlLabel
                      control={
                        <Switch
                          checked={editableConfig.hsts_enabled}
                          onChange={(e) => setEditableConfig({ ...editableConfig, hsts_enabled: e.target.checked })}
                        />
                      }
                      label={t('security.enableHSTS')}
                    />
                  </Grid>
                  <Grid item xs={12} md={4}>
                    <TextField
                      fullWidth
                      type="number"
                      label={t('security.maxAge')}
                      value={editableConfig.hsts_max_age}
                      onChange={(e) => setEditableConfig({ ...editableConfig, hsts_max_age: parseInt(e.target.value) })}
                    />
                  </Grid>
                  <Grid item xs={12} md={4}>
                    <FormControlLabel
                      control={
                        <Switch
                          checked={editableConfig.hsts_include_subdomains}
                          onChange={(e) => setEditableConfig({ ...editableConfig, hsts_include_subdomains: e.target.checked })}
                        />
                      }
                      label={t('security.includeSubdomains')}
                    />
                  </Grid>
                  <Grid item xs={12} md={4}>
                    <FormControlLabel
                      control={
                        <Switch
                          checked={editableConfig.hsts_preload}
                          onChange={(e) => setEditableConfig({ ...editableConfig, hsts_preload: e.target.checked })}
                        />
                      }
                      label={t('security.preload')}
                    />
                  </Grid>
                </Grid>

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

                <Typography variant="h6" gutterBottom>
                  {t('security.otherHeaders')}
                </Typography>
                <Grid container spacing={2}>
                  <Grid item xs={12} md={6}>
                    <FormControl fullWidth>
                      <InputLabel>{t('security.referrerPolicy')}</InputLabel>
                      <Select
                        value={editableConfig.referrer_policy}
                        label={t('security.referrerPolicy')}
                        onChange={(e) => setEditableConfig({ ...editableConfig, referrer_policy: e.target.value })}
                      >
                        <MenuItem value="no-referrer">no-referrer</MenuItem>
                        <MenuItem value="no-referrer-when-downgrade">no-referrer-when-downgrade</MenuItem>
                        <MenuItem value="origin">origin</MenuItem>
                        <MenuItem value="origin-when-cross-origin">origin-when-cross-origin</MenuItem>
                        <MenuItem value="same-origin">same-origin</MenuItem>
                        <MenuItem value="strict-origin">strict-origin</MenuItem>
                        <MenuItem value="strict-origin-when-cross-origin">strict-origin-when-cross-origin</MenuItem>
                      </Select>
                    </FormControl>
                  </Grid>
                  <Grid item xs={12} md={6}>
                    <FormControl fullWidth>
                      <InputLabel>{t('security.xFrameOptions')}</InputLabel>
                      <Select
                        value={editableConfig.x_frame_options}
                        label={t('security.xFrameOptions')}
                        onChange={(e) => setEditableConfig({ ...editableConfig, x_frame_options: e.target.value })}
                      >
                        <MenuItem value="DENY">DENY</MenuItem>
                        <MenuItem value="SAMEORIGIN">SAMEORIGIN</MenuItem>
                      </Select>
                    </FormControl>
                  </Grid>
                  <Grid item xs={12} md={6}>
                    <FormControlLabel
                      control={
                        <Switch
                          checked={editableConfig.x_content_type_options}
                          onChange={(e) => setEditableConfig({ ...editableConfig, x_content_type_options: e.target.checked })}
                        />
                      }
                      label="X-Content-Type-Options: nosniff"
                    />
                  </Grid>
                  <Grid item xs={12} md={6}>
                    <FormControlLabel
                      control={
                        <Switch
                          checked={editableConfig.x_xss_protection}
                          onChange={(e) => setEditableConfig({ ...editableConfig, x_xss_protection: e.target.checked })}
                        />
                      }
                      label="X-XSS-Protection"
                    />
                  </Grid>
                </Grid>
              </Box>
            )}
          </CardContent>
        </TabPanel>

        {/* Saved Configurations Tab */}
        <TabPanel value={tabValue} index={2}>
          <CardContent>
            {savedConfigs.length === 0 ? (
              <Alert severity="info">{t('security.noSavedConfigs')}</Alert>
            ) : (
              <Grid container spacing={2}>
                {savedConfigs.map((config) => (
                  <Grid item xs={12} key={config.id}>
                    <Card variant="outlined">
                      <CardContent>
                        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                          <Box>
                            <Typography variant="h6">
                              {config.config_name}
                              {config.is_active && (
                                <Chip label={t('security.active')} color="success" size="small" sx={{ ml: 1 }} />
                              )}
                            </Typography>
                            <Typography variant="caption" color="text.secondary">
                              {t('security.created')}: {new Date(config.created_at).toLocaleString()}
                            </Typography>
                          </Box>
                          <Box sx={{ display: 'flex', gap: 1 }}>
                            <Button
                              size="small"
                              startIcon={<ContentCopy />}
                              onClick={() => {
                                setEditableConfig({
                                  csp_default_src: config.csp_default_src,
                                  csp_script_src: config.csp_script_src,
                                  csp_style_src: config.csp_style_src,
                                  csp_img_src: config.csp_img_src,
                                  csp_media_src: config.csp_media_src,
                                  csp_connect_src: config.csp_connect_src,
                                  csp_font_src: config.csp_font_src,
                                  csp_frame_src: config.csp_frame_src,
                                  csp_object_src: config.csp_object_src,
                                  csp_base_uri: config.csp_base_uri,
                                  csp_form_action: config.csp_form_action,
                                  csp_frame_ancestors: config.csp_frame_ancestors,
                                  hsts_enabled: config.hsts_enabled,
                                  hsts_max_age: config.hsts_max_age,
                                  hsts_include_subdomains: config.hsts_include_subdomains,
                                  hsts_preload: config.hsts_preload,
                                  referrer_policy: config.referrer_policy,
                                  x_content_type_options: config.x_content_type_options,
                                  x_frame_options: config.x_frame_options,
                                  x_xss_protection: config.x_xss_protection
                                });
                                setTabValue(1);
                                setSuccess(t('security.configLoaded'));
                              }}
                            >
                              {t('security.loadToEditor')}
                            </Button>
                            {!config.is_active && (
                              <>
                                <Button
                                  size="small"
                                  variant="contained"
                                  onClick={() => handleApplyConfiguration(config.id)}
                                >
                                  {t('security.apply')}
                                </Button>
                                <IconButton
                                  size="small"
                                  color="error"
                                  onClick={() => handleDeleteConfiguration(config.id)}
                                >
                                  <Delete />
                                </IconButton>
                              </>
                            )}
                          </Box>
                        </Box>
                      </CardContent>
                    </Card>
                  </Grid>
                ))}
              </Grid>
            )}
          </CardContent>
        </TabPanel>

        {/* Recommendations Tab */}
        <TabPanel value={tabValue} index={3}>
          <CardContent>
            {recommendations && recommendations.recommendations.length > 0 ? (
              <List>
                {recommendations.recommendations.map((rec, index) => (
                  <React.Fragment key={index}>
                    <Accordion>
                      <AccordionSummary expandIcon={<ExpandMore />}>
                        <Box sx={{ display: 'flex', alignItems: 'center', gap: 2, width: '100%' }}>
                          <Box sx={{ color: `${getSeverityColor(rec.severity)}.main` }}>
                            {getSeverityIcon(rec.severity)}
                          </Box>
                          <Box sx={{ flex: 1 }}>
                            <Typography variant="subtitle1" fontWeight="medium">
                              {rec.title}
                            </Typography>
                            <Box sx={{ display: 'flex', gap: 1, mt: 0.5 }}>
                              <Chip
                                label={rec.category}
                                size="small"
                                variant="outlined"
                              />
                              <Chip
                                label={`${rec.severity.toUpperCase()}`}
                                size="small"
                                color={getSeverityColor(rec.severity)}
                              />
                              {rec.impact && (
                                <Chip
                                  label={`Impact: ${rec.impact}`}
                                  size="small"
                                  variant="outlined"
                                />
                              )}
                            </Box>
                          </Box>
                        </Box>
                      </AccordionSummary>
                      <AccordionDetails>
                        <Box sx={{ pl: 5 }}>
                          <Typography variant="body2" color="text.secondary" paragraph>
                            <strong>Description:</strong>
                          </Typography>
                          <Typography variant="body2" paragraph sx={{ whiteSpace: 'pre-line' }}>
                            {rec.description}
                          </Typography>

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

                          <Typography variant="body2" color="primary.main" paragraph>
                            <strong>Recommended Action:</strong>
                          </Typography>
                          <Typography variant="body2" paragraph sx={{ whiteSpace: 'pre-line' }}>
                            {rec.action}
                          </Typography>

                          {rec.details && (
                            <>
                              <Divider sx={{ my: 2 }} />
                              <Typography variant="body2" color="text.secondary" paragraph>
                                <strong>Additional Details:</strong>
                              </Typography>
                              <Box sx={{ 
                                bgcolor: (theme) => theme.palette.mode === 'dark' ? 'grey.900' : 'grey.50',
                                border: (theme) => `1px solid ${theme.palette.divider}`,
                                p: 2, 
                                borderRadius: 1 
                              }}>
                                {Object.entries(rec.details).map(([key, value]) => (
                                  <Box key={key} sx={{ mb: 1 }}>
                                    <Typography variant="caption" color="primary" display="block" fontWeight="medium">
                                      {key.replace(/([A-Z])/g, ' $1').replace(/^./, str => str.toUpperCase())}:
                                    </Typography>
                                    <Typography variant="body2" color="text.primary">{value}</Typography>
                                  </Box>
                                ))}
                              </Box>
                            </>
                          )}
                        </Box>
                      </AccordionDetails>
                    </Accordion>
                  </React.Fragment>
                ))}
              </List>
            ) : (
              <Alert severity="success">{t('security.noRecommendations')}</Alert>
            )}
          </CardContent>
        </TabPanel>

        {/* History Tab */}
        <TabPanel value={tabValue} index={4}>
          <CardContent>
            {history.length === 0 ? (
              <Alert severity="info">{t('security.noHistory')}</Alert>
            ) : (
              <TableContainer>
                <Table>
                  <TableHead>
                    <TableRow>
                      <TableCell>{t('security.timestamp')}</TableCell>
                      <TableCell>{t('security.action')}</TableCell>
                      <TableCell>{t('security.configuration')}</TableCell>
                      <TableCell>{t('security.changedBy')}</TableCell>
                    </TableRow>
                  </TableHead>
                  <TableBody>
                    {history.map((entry) => (
                      <TableRow key={entry.id}>
                        <TableCell>{new Date(entry.timestamp).toLocaleString()}</TableCell>
                        <TableCell>
                          <Chip label={entry.action} size="small" />
                        </TableCell>
                        <TableCell>{entry.config_name || '-'}</TableCell>
                        <TableCell>{entry.username || '-'}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </TableContainer>
            )}
          </CardContent>
        </TabPanel>
      </Card>

      {/* Save Dialog */}
      <Dialog open={saveDialogOpen} onClose={() => setSaveDialogOpen(false)} maxWidth="sm" fullWidth>
        <DialogTitle>{t('security.saveConfiguration')}</DialogTitle>
        <DialogContent>
          <TextField
            fullWidth
            label={t('security.configurationName')}
            value={configName}
            onChange={(e) => setConfigName(e.target.value)}
            sx={{ mt: 2 }}
            helperText={t('security.configNameHelper')}
          />
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setSaveDialogOpen(false)}>{t('common.cancel')}</Button>
          <Button onClick={handleSaveConfiguration} variant="contained">
            {t('common.save')}
          </Button>
        </DialogActions>
      </Dialog>

      {/* Test Results Dialog */}
      <Dialog open={testDialogOpen} onClose={() => setTestDialogOpen(false)} maxWidth="md" fullWidth>
        <DialogTitle>{t('security.testResults')}</DialogTitle>
        <DialogContent>
          {testResults && (
            <Box>
              <Box sx={{ mb: 3, textAlign: 'center' }}>
                <Typography variant="h3" fontWeight="bold" color="primary.main">
                  {testResults.score}
                </Typography>
                <Typography variant="h6">
                  {t('security.grade')}: {testResults.grade}
                </Typography>
                <Typography variant="body2" color="text.secondary">
                  {testResults.summary}
                </Typography>
              </Box>

              {testResults.passed.length > 0 && (
                <Box sx={{ mb: 2 }}>
                  <Typography variant="subtitle1" fontWeight="medium" color="success.main" gutterBottom>
                    ✓ {t('security.passed')}
                  </Typography>
                  {testResults.passed.map((item, index) => (
                    <Alert key={index} severity="success" sx={{ mb: 1 }}>
                      <strong>{item.test}</strong>: {item.message}
                    </Alert>
                  ))}
                </Box>
              )}

              {testResults.warnings.length > 0 && (
                <Box sx={{ mb: 2 }}>
                  <Typography variant="subtitle1" fontWeight="medium" color="warning.main" gutterBottom>
                    ⚠ {t('security.warnings')}
                  </Typography>
                  {testResults.warnings.map((item, index) => (
                    <Alert key={index} severity="warning" sx={{ mb: 1 }}>
                      <strong>{item.test}</strong>: {item.message}
                    </Alert>
                  ))}
                </Box>
              )}

              {testResults.errors.length > 0 && (
                <Box>
                  <Typography variant="subtitle1" fontWeight="medium" color="error.main" gutterBottom>
                    ✗ {t('security.errors')}
                  </Typography>
                  {testResults.errors.map((item, index) => (
                    <Alert key={index} severity="error" sx={{ mb: 1 }}>
                      <strong>{item.test}</strong>: {item.message}
                    </Alert>
                  ))}
                </Box>
              )}
            </Box>
          )}
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setTestDialogOpen(false)}>{t('common.close')}</Button>
        </DialogActions>
      </Dialog>

      {/* Preset Selection Dialog */}
      <Dialog open={presetDialogOpen} onClose={() => setPresetDialogOpen(false)} maxWidth="sm" fullWidth>
        <DialogTitle>{t('security.selectPreset')}</DialogTitle>
        <DialogContent>
          <FormControl fullWidth sx={{ mt: 2 }}>
            <InputLabel>{t('security.preset')}</InputLabel>
            <Select
              value={selectedPreset}
              label={t('security.preset')}
              onChange={(e) => setSelectedPreset(e.target.value)}
            >
              {Object.entries(presets).map(([key, preset]) => (
                <MenuItem key={key} value={key}>
                  <Box>
                    <Typography variant="subtitle2">{preset.name}</Typography>
                    <Typography variant="caption" color="text.secondary">
                      {preset.description}
                    </Typography>
                  </Box>
                </MenuItem>
              ))}
            </Select>
          </FormControl>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setPresetDialogOpen(false)}>{t('common.cancel')}</Button>
          <Button onClick={handleApplyPreset} variant="contained" disabled={!selectedPreset}>
            {t('security.loadPreset')}
          </Button>
        </DialogActions>
      </Dialog>
    </Container>
  );
};

export default SecurityHeadersDashboard;
