import React, { useState, useEffect } from 'react';
import {
  Box, Container, Typography, Card, CardContent, Grid, Table, TableBody, TableCell,
  TableContainer, TableHead, TableRow, Paper, Chip, CircularProgress, Alert, IconButton,
  Tabs, Tab, Button, Dialog, DialogTitle, DialogContent, DialogActions, TextField,
  Select, MenuItem, FormControl, InputLabel, Switch, FormControlLabel, Tooltip
} from '@mui/material';
import {
  Settings, Add, Edit, Delete, Refresh, Warning, CheckCircle, Security, PlayArrow
} from '@mui/icons-material';
import { useTranslation } from 'react-i18next';
import { useAuthStore } from '../store/authStore';
import { useNavigate } from 'react-router-dom';
import axios from 'axios';
import { format } from 'date-fns';

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

const SecurityConfigDashboard = () => {
  const { t } = useTranslation();
  const { token, user } = useAuthStore();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  const [tabValue, setTabValue] = useState(0);

  // Data states
  const [thresholds, setThresholds] = useState([]);
  const [signatures, setSignatures] = useState([]);
  const [protocols, setProtocols] = useState([]);
  const [stats, setStats] = useState(null);

  // Dialog states
  const [thresholdDialog, setThresholdDialog] = useState({ open: false, mode: 'add', data: null });
  const [signatureDialog, setSignatureDialog] = useState({ open: false, mode: 'add', data: null });
  const [protocolDialog, setProtocolDialog] = useState({ open: false, mode: 'add', data: null });
  const [deleteDialog, setDeleteDialog] = useState({ open: false, type: null, id: null });

  // Redirect non-admins
  useEffect(() => {
    if (user?.role !== 'admin') {
      navigate('/');
    }
  }, [user, navigate]);

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

  const fetchAllData = async () => {
    setLoading(true);
    setError('');
    try {
      const [thresholdsRes, signaturesRes, protocolsRes, dashboardRes] = await Promise.all([
        axios.get('/api/security-config/thresholds', { headers: { Authorization: `Bearer ${token}` } }),
        axios.get('/api/security-config/signatures', { headers: { Authorization: `Bearer ${token}` } }),
        axios.get('/api/security-config/protocols', { headers: { Authorization: `Bearer ${token}` } }),
        axios.get('/api/security-config/dashboard', { headers: { Authorization: `Bearer ${token}` } })
      ]);

      setThresholds(thresholdsRes.data.data);
      setSignatures(signaturesRes.data.data);
      setProtocols(protocolsRes.data.data);
      setStats(dashboardRes.data.data);
    } catch (err) {
      setError(err.response?.data?.message || t('common.error'));
    } finally {
      setLoading(false);
    }
  };

  const handleSaveThreshold = async () => {
    try {
      const url = thresholdDialog.mode === 'add' 
        ? '/api/security-config/thresholds'
        : `/api/security-config/thresholds/${thresholdDialog.data.threshold_id}`;
      
      const method = thresholdDialog.mode === 'add' ? 'post' : 'put';
      
      await axios[method](url, thresholdDialog.data, {
        headers: { Authorization: `Bearer ${token}` }
      });

      setSuccess(t('securityConfig.thresholdSaved'));
      setThresholdDialog({ open: false, mode: 'add', data: null });
      fetchAllData();
    } catch (err) {
      setError(err.response?.data?.message || t('common.error'));
    }
  };

  const handleSaveSignature = async () => {
    try {
      const url = signatureDialog.mode === 'add'
        ? '/api/security-config/signatures'
        : `/api/security-config/signatures/${signatureDialog.data.signature_id}`;
      
      const method = signatureDialog.mode === 'add' ? 'post' : 'put';
      
      await axios[method](url, signatureDialog.data, {
        headers: { Authorization: `Bearer ${token}` }
      });

      setSuccess(t('securityConfig.signatureSaved'));
      setSignatureDialog({ open: false, mode: 'add', data: null });
      fetchAllData();
    } catch (err) {
      setError(err.response?.data?.message || t('common.error'));
    }
  };

  const handleSaveProtocol = async () => {
    try {
      const url = protocolDialog.mode === 'add'
        ? '/api/security-config/protocols'
        : `/api/security-config/protocols/${protocolDialog.data.protocol_id}`;
      
      const method = protocolDialog.mode === 'add' ? 'post' : 'put';
      
      await axios[method](url, protocolDialog.data, {
        headers: { Authorization: `Bearer ${token}` }
      });

      setSuccess(t('securityConfig.protocolSaved'));
      setProtocolDialog({ open: false, mode: 'add', data: null });
      fetchAllData();
    } catch (err) {
      setError(err.response?.data?.message || t('common.error'));
    }
  };

  const handleDelete = async () => {
    try {
      const urls = {
        threshold: `/api/security-config/thresholds/${deleteDialog.id}`,
        signature: `/api/security-config/signatures/${deleteDialog.id}`,
        protocol: `/api/security-config/protocols/${deleteDialog.id}`
      };

      await axios.delete(urls[deleteDialog.type], {
        headers: { Authorization: `Bearer ${token}` }
      });

      setSuccess(t('securityConfig.deleted'));
      setDeleteDialog({ open: false, type: null, id: null });
      fetchAllData();
    } catch (err) {
      setError(err.response?.data?.message || t('common.error'));
    }
  };

  const getSeverityColor = (severity) => {
    const colors = { critical: 'error', high: 'warning', medium: 'info', low: 'success' };
    return colors[severity] || 'default';
  };

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

  return (
    <Container maxWidth="xl" sx={{ mt: 4, mb: 4 }}>
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
          <Settings fontSize="large" color="primary" />
          <Typography variant="h4">{t('securityConfig.title')}</Typography>
        </Box>
        <Button variant="contained" startIcon={<Refresh />} onClick={fetchAllData}>
          {t('common.refresh')}
        </Button>
      </Box>

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

      {/* Statistics Cards */}
      {stats && (
        <Grid container spacing={3} sx={{ mb: 3 }}>
          <Grid item xs={12} md={4}>
            <Card>
              <CardContent>
                <Typography variant="h6" gutterBottom>{t('securityConfig.thresholds')}</Typography>
                <Typography variant="h3" color="primary">{stats.thresholds.total}</Typography>
                <Typography variant="body2" color="text.secondary">
                  {stats.thresholds.enabled} {t('securityConfig.enabled')}
                </Typography>
              </CardContent>
            </Card>
          </Grid>
          <Grid item xs={12} md={4}>
            <Card>
              <CardContent>
                <Typography variant="h6" gutterBottom>{t('securityConfig.signatures')}</Typography>
                <Typography variant="h3" color="warning.main">{stats.signatures.total}</Typography>
                <Typography variant="body2" color="text.secondary">
                  {stats.signatures.auto_block_enabled} {t('securityConfig.autoBlock')}
                </Typography>
              </CardContent>
            </Card>
          </Grid>
          <Grid item xs={12} md={4}>
            <Card>
              <CardContent>
                <Typography variant="h6" gutterBottom>{t('securityConfig.protocols')}</Typography>
                <Typography variant="h3" color="error.main">{stats.protocols.total}</Typography>
                <Typography variant="body2" color="text.secondary">
                  {stats.protocols.auto_execute_enabled} {t('securityConfig.autoExecute')}
                </Typography>
              </CardContent>
            </Card>
          </Grid>
        </Grid>
      )}

      {/* Tabs */}
      <Paper>
        <Tabs value={tabValue} onChange={(e, v) => setTabValue(v)} variant="fullWidth">
          <Tab label={t('securityConfig.thresholds')} />
          <Tab label={t('securityConfig.signatures')} />
          <Tab label={t('securityConfig.protocols')} />
        </Tabs>

        {/* Thresholds Tab */}
        <TabPanel value={tabValue} index={0}>
          <Box sx={{ p: 2 }}>
            <Button 
              variant="contained" 
              startIcon={<Add />}
              onClick={() => setThresholdDialog({ 
                open: true, 
                mode: 'add', 
                data: { 
                  name: '', description: '', pattern_type: 'brute_force_attack', 
                  metric_name: 'failed_login_count', operator: '>=', threshold_value: 5,
                  time_window_minutes: 10, severity: 'high', enabled: true 
                } 
              })}
              sx={{ mb: 2 }}
            >
              {t('securityConfig.addThreshold')}
            </Button>
            
            <TableContainer>
              <Table>
                <TableHead>
                  <TableRow>
                    <TableCell>{t('securityConfig.name')}</TableCell>
                    <TableCell>{t('securityConfig.patternType')}</TableCell>
                    <TableCell>{t('securityConfig.condition')}</TableCell>
                    <TableCell>{t('securityConfig.timeWindow')}</TableCell>
                    <TableCell>{t('securityConfig.severity')}</TableCell>
                    <TableCell>{t('securityConfig.status')}</TableCell>
                    <TableCell>{t('common.actions')}</TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  {thresholds.map((threshold) => (
                    <TableRow key={threshold.id}>
                      <TableCell>{threshold.name}</TableCell>
                      <TableCell><Chip label={threshold.pattern_type} size="small" /></TableCell>
                      <TableCell>
                        {threshold.metric_name} {threshold.operator} {threshold.threshold_value}
                      </TableCell>
                      <TableCell>{threshold.time_window_minutes} min</TableCell>
                      <TableCell>
                        <Chip label={threshold.severity} color={getSeverityColor(threshold.severity)} size="small" />
                      </TableCell>
                      <TableCell>
                        <Chip 
                          label={threshold.enabled ? t('common.enabled') : t('common.disabled')}
                          color={threshold.enabled ? 'success' : 'default'}
                          size="small"
                        />
                      </TableCell>
                      <TableCell>
                        <IconButton size="small" onClick={() => setThresholdDialog({ open: true, mode: 'edit', data: threshold })}>
                          <Edit />
                        </IconButton>
                        <IconButton size="small" color="error" onClick={() => setDeleteDialog({ open: true, type: 'threshold', id: threshold.threshold_id })}>
                          <Delete />
                        </IconButton>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </TableContainer>
          </Box>
        </TabPanel>

        {/* Signatures Tab */}
        <TabPanel value={tabValue} index={1}>
          <Box sx={{ p: 2 }}>
            <Button 
              variant="contained" 
              startIcon={<Add />}
              onClick={() => setSignatureDialog({ 
                open: true, 
                mode: 'add', 
                data: { 
                  name: '', description: '', signature_type: 'attack_pattern', 
                  pattern: '', match_type: 'regex', threat_level: 'high',
                  confidence: 0.8, enabled: true, auto_block: false 
                } 
              })}
              sx={{ mb: 2 }}
            >
              {t('securityConfig.addSignature')}
            </Button>
            
            <TableContainer>
              <Table>
                <TableHead>
                  <TableRow>
                    <TableCell>{t('securityConfig.name')}</TableCell>
                    <TableCell>{t('securityConfig.signatureType')}</TableCell>
                    <TableCell>{t('securityConfig.matchType')}</TableCell>
                    <TableCell>{t('securityConfig.threatLevel')}</TableCell>
                    <TableCell>{t('securityConfig.confidence')}</TableCell>
                    <TableCell>{t('securityConfig.autoBlock')}</TableCell>
                    <TableCell>{t('securityConfig.status')}</TableCell>
                    <TableCell>{t('common.actions')}</TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  {signatures.map((signature) => (
                    <TableRow key={signature.id}>
                      <TableCell>{signature.name}</TableCell>
                      <TableCell><Chip label={signature.signature_type} size="small" /></TableCell>
                      <TableCell>{signature.match_type}</TableCell>
                      <TableCell>
                        <Chip label={signature.threat_level} color={getSeverityColor(signature.threat_level)} size="small" />
                      </TableCell>
                      <TableCell>{(signature.confidence * 100).toFixed(0)}%</TableCell>
                      <TableCell>
                        {signature.auto_block ? <CheckCircle color="warning" /> : '-'}
                      </TableCell>
                      <TableCell>
                        <Chip 
                          label={signature.enabled ? t('common.enabled') : t('common.disabled')}
                          color={signature.enabled ? 'success' : 'default'}
                          size="small"
                        />
                      </TableCell>
                      <TableCell>
                        <IconButton size="small" onClick={() => setSignatureDialog({ open: true, mode: 'edit', data: signature })}>
                          <Edit />
                        </IconButton>
                        <IconButton size="small" color="error" onClick={() => setDeleteDialog({ open: true, type: 'signature', id: signature.signature_id })}>
                          <Delete />
                        </IconButton>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </TableContainer>
          </Box>
        </TabPanel>

        {/* Protocols Tab */}
        <TabPanel value={tabValue} index={2}>
          <Box sx={{ p: 2 }}>
            <Button 
              variant="contained" 
              startIcon={<Add />}
              onClick={() => setProtocolDialog({ 
                open: true, 
                mode: 'add', 
                data: { 
                  name: '', description: '', trigger_type: 'anomaly', 
                  trigger_condition: {}, actions: [],
                  severity: 'high', enabled: true, auto_execute: false, cooldown_minutes: 60 
                } 
              })}
              sx={{ mb: 2 }}
            >
              {t('securityConfig.addProtocol')}
            </Button>
            
            <TableContainer>
              <Table>
                <TableHead>
                  <TableRow>
                    <TableCell>{t('securityConfig.name')}</TableCell>
                    <TableCell>{t('securityConfig.triggerType')}</TableCell>
                    <TableCell>{t('securityConfig.actionsCount')}</TableCell>
                    <TableCell>{t('securityConfig.severity')}</TableCell>
                    <TableCell>{t('securityConfig.autoExecute')}</TableCell>
                    <TableCell>{t('securityConfig.cooldown')}</TableCell>
                    <TableCell>{t('securityConfig.status')}</TableCell>
                    <TableCell>{t('common.actions')}</TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  {protocols.map((protocol) => {
                    const actions = typeof protocol.actions === 'string' ? JSON.parse(protocol.actions) : protocol.actions;
                    return (
                      <TableRow key={protocol.id}>
                        <TableCell>{protocol.name}</TableCell>
                        <TableCell><Chip label={protocol.trigger_type} size="small" /></TableCell>
                        <TableCell>{actions.length} {t('securityConfig.actions')}</TableCell>
                        <TableCell>
                          <Chip label={protocol.severity} color={getSeverityColor(protocol.severity)} size="small" />
                        </TableCell>
                        <TableCell>
                          {protocol.auto_execute ? <PlayArrow color="success" /> : '-'}
                        </TableCell>
                        <TableCell>{protocol.cooldown_minutes} min</TableCell>
                        <TableCell>
                          <Chip 
                            label={protocol.enabled ? t('common.enabled') : t('common.disabled')}
                            color={protocol.enabled ? 'success' : 'default'}
                            size="small"
                          />
                        </TableCell>
                        <TableCell>
                          <IconButton size="small" onClick={() => setProtocolDialog({ open: true, mode: 'edit', data: protocol })}>
                            <Edit />
                          </IconButton>
                          <IconButton size="small" color="error" onClick={() => setDeleteDialog({ open: true, type: 'protocol', id: protocol.protocol_id })}>
                            <Delete />
                          </IconButton>
                        </TableCell>
                      </TableRow>
                    );
                  })}
                </TableBody>
              </Table>
            </TableContainer>
          </Box>
        </TabPanel>
      </Paper>

      {/* Threshold Dialog */}
      <Dialog open={thresholdDialog.open} onClose={() => setThresholdDialog({ open: false, mode: 'add', data: null })} maxWidth="sm" fullWidth>
        <DialogTitle>
          {thresholdDialog.mode === 'add' ? t('securityConfig.addThreshold') : t('securityConfig.editThreshold')}
        </DialogTitle>
        <DialogContent>
          <TextField
            fullWidth
            margin="normal"
            label={t('securityConfig.name')}
            value={thresholdDialog.data?.name || ''}
            onChange={(e) => setThresholdDialog({ ...thresholdDialog, data: { ...thresholdDialog.data, name: e.target.value } })}
          />
          <TextField
            fullWidth
            margin="normal"
            label={t('securityConfig.description')}
            multiline
            rows={2}
            value={thresholdDialog.data?.description || ''}
            onChange={(e) => setThresholdDialog({ ...thresholdDialog, data: { ...thresholdDialog.data, description: e.target.value } })}
          />
          <FormControl fullWidth margin="normal">
            <InputLabel>{t('securityConfig.patternType')}</InputLabel>
            <Select
              value={thresholdDialog.data?.pattern_type || 'brute_force_attack'}
              onChange={(e) => setThresholdDialog({ ...thresholdDialog, data: { ...thresholdDialog.data, pattern_type: e.target.value } })}
            >
              <MenuItem value="brute_force_attack">Brute Force Attack</MenuItem>
              <MenuItem value="credential_stuffing">Credential Stuffing</MenuItem>
              <MenuItem value="privilege_escalation">Privilege Escalation</MenuItem>
              <MenuItem value="suspicious_ip">Suspicious IP</MenuItem>
              <MenuItem value="data_exfiltration">Data Exfiltration</MenuItem>
            </Select>
          </FormControl>
          <TextField
            fullWidth
            margin="normal"
            label={t('securityConfig.metricName')}
            value={thresholdDialog.data?.metric_name || ''}
            onChange={(e) => setThresholdDialog({ ...thresholdDialog, data: { ...thresholdDialog.data, metric_name: e.target.value } })}
          />
          <Grid container spacing={2}>
            <Grid item xs={6}>
              <FormControl fullWidth margin="normal">
                <InputLabel>{t('securityConfig.operator')}</InputLabel>
                <Select
                  value={thresholdDialog.data?.operator || '>='}
                  onChange={(e) => setThresholdDialog({ ...thresholdDialog, data: { ...thresholdDialog.data, operator: e.target.value } })}
                >
                  <MenuItem value=">=">&gt;=</MenuItem>
                  <MenuItem value=">">&gt;</MenuItem>
                  <MenuItem value="<=">&lt;=</MenuItem>
                  <MenuItem value="<">&lt;</MenuItem>
                  <MenuItem value="==">==</MenuItem>
                  <MenuItem value="!=">!=</MenuItem>
                </Select>
              </FormControl>
            </Grid>
            <Grid item xs={6}>
              <TextField
                fullWidth
                margin="normal"
                type="number"
                label={t('securityConfig.thresholdValue')}
                value={thresholdDialog.data?.threshold_value || 0}
                onChange={(e) => setThresholdDialog({ ...thresholdDialog, data: { ...thresholdDialog.data, threshold_value: parseInt(e.target.value) } })}
              />
            </Grid>
          </Grid>
          <Grid container spacing={2}>
            <Grid item xs={6}>
              <TextField
                fullWidth
                margin="normal"
                type="number"
                label={t('securityConfig.timeWindow')}
                value={thresholdDialog.data?.time_window_minutes || 30}
                onChange={(e) => setThresholdDialog({ ...thresholdDialog, data: { ...thresholdDialog.data, time_window_minutes: parseInt(e.target.value) } })}
              />
            </Grid>
            <Grid item xs={6}>
              <FormControl fullWidth margin="normal">
                <InputLabel>{t('securityConfig.severity')}</InputLabel>
                <Select
                  value={thresholdDialog.data?.severity || 'high'}
                  onChange={(e) => setThresholdDialog({ ...thresholdDialog, data: { ...thresholdDialog.data, severity: e.target.value } })}
                >
                  <MenuItem value="low">Low</MenuItem>
                  <MenuItem value="medium">Medium</MenuItem>
                  <MenuItem value="high">High</MenuItem>
                  <MenuItem value="critical">Critical</MenuItem>
                </Select>
              </FormControl>
            </Grid>
          </Grid>
          <FormControlLabel
            control={
              <Switch
                checked={thresholdDialog.data?.enabled || false}
                onChange={(e) => setThresholdDialog({ ...thresholdDialog, data: { ...thresholdDialog.data, enabled: e.target.checked } })}
              />
            }
            label={t('common.enabled')}
          />
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setThresholdDialog({ open: false, mode: 'add', data: null })}>{t('common.cancel')}</Button>
          <Button variant="contained" onClick={handleSaveThreshold}>{t('common.save')}</Button>
        </DialogActions>
      </Dialog>

      {/* Signature Dialog */}
      <Dialog open={signatureDialog.open} onClose={() => setSignatureDialog({ open: false, mode: 'add', data: null })} maxWidth="md" fullWidth>
        <DialogTitle>
          {signatureDialog.mode === 'add' ? t('securityConfig.addSignature') : t('securityConfig.editSignature')}
        </DialogTitle>
        <DialogContent>
          <TextField
            fullWidth
            margin="normal"
            label={t('securityConfig.name')}
            value={signatureDialog.data?.name || ''}
            onChange={(e) => setSignatureDialog({ ...signatureDialog, data: { ...signatureDialog.data, name: e.target.value } })}
          />
          <TextField
            fullWidth
            margin="normal"
            label={t('securityConfig.description')}
            multiline
            rows={2}
            value={signatureDialog.data?.description || ''}
            onChange={(e) => setSignatureDialog({ ...signatureDialog, data: { ...signatureDialog.data, description: e.target.value } })}
          />
          <Grid container spacing={2}>
            <Grid item xs={6}>
              <FormControl fullWidth margin="normal">
                <InputLabel>{t('securityConfig.signatureType')}</InputLabel>
                <Select
                  value={signatureDialog.data?.signature_type || 'attack_pattern'}
                  onChange={(e) => setSignatureDialog({ ...signatureDialog, data: { ...signatureDialog.data, signature_type: e.target.value } })}
                >
                  <MenuItem value="ip_address">IP Address</MenuItem>
                  <MenuItem value="user_agent">User Agent</MenuItem>
                  <MenuItem value="attack_pattern">Attack Pattern</MenuItem>
                  <MenuItem value="behavior">Behavior</MenuItem>
                </Select>
              </FormControl>
            </Grid>
            <Grid item xs={6}>
              <FormControl fullWidth margin="normal">
                <InputLabel>{t('securityConfig.matchType')}</InputLabel>
                <Select
                  value={signatureDialog.data?.match_type || 'regex'}
                  onChange={(e) => setSignatureDialog({ ...signatureDialog, data: { ...signatureDialog.data, match_type: e.target.value } })}
                >
                  <MenuItem value="regex">Regex</MenuItem>
                  <MenuItem value="regex_case_insensitive">Regex (Case Insensitive)</MenuItem>
                  <MenuItem value="exact">Exact Match</MenuItem>
                  <MenuItem value="contains">Contains</MenuItem>
                  <MenuItem value="custom">Custom</MenuItem>
                </Select>
              </FormControl>
            </Grid>
          </Grid>
          <TextField
            fullWidth
            margin="normal"
            label={t('securityConfig.pattern')}
            multiline
            rows={3}
            value={signatureDialog.data?.pattern || ''}
            onChange={(e) => setSignatureDialog({ ...signatureDialog, data: { ...signatureDialog.data, pattern: e.target.value } })}
            helperText={t('securityConfig.patternHelp')}
          />
          <Grid container spacing={2}>
            <Grid item xs={4}>
              <FormControl fullWidth margin="normal">
                <InputLabel>{t('securityConfig.threatLevel')}</InputLabel>
                <Select
                  value={signatureDialog.data?.threat_level || 'high'}
                  onChange={(e) => setSignatureDialog({ ...signatureDialog, data: { ...signatureDialog.data, threat_level: e.target.value } })}
                >
                  <MenuItem value="low">Low</MenuItem>
                  <MenuItem value="medium">Medium</MenuItem>
                  <MenuItem value="high">High</MenuItem>
                  <MenuItem value="critical">Critical</MenuItem>
                </Select>
              </FormControl>
            </Grid>
            <Grid item xs={4}>
              <TextField
                fullWidth
                margin="normal"
                type="number"
                label={t('securityConfig.confidence')}
                value={signatureDialog.data?.confidence || 0.8}
                onChange={(e) => setSignatureDialog({ ...signatureDialog, data: { ...signatureDialog.data, confidence: parseFloat(e.target.value) } })}
                inputProps={{ min: 0, max: 1, step: 0.1 }}
              />
            </Grid>
            <Grid item xs={4}>
              <Box sx={{ mt: 2 }}>
                <FormControlLabel
                  control={
                    <Switch
                      checked={signatureDialog.data?.auto_block || false}
                      onChange={(e) => setSignatureDialog({ ...signatureDialog, data: { ...signatureDialog.data, auto_block: e.target.checked } })}
                    />
                  }
                  label={t('securityConfig.autoBlock')}
                />
              </Box>
            </Grid>
          </Grid>
          <FormControlLabel
            control={
              <Switch
                checked={signatureDialog.data?.enabled || false}
                onChange={(e) => setSignatureDialog({ ...signatureDialog, data: { ...signatureDialog.data, enabled: e.target.checked } })}
              />
            }
            label={t('common.enabled')}
          />
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setSignatureDialog({ open: false, mode: 'add', data: null })}>{t('common.cancel')}</Button>
          <Button variant="contained" onClick={handleSaveSignature}>{t('common.save')}</Button>
        </DialogActions>
      </Dialog>

      {/* Protocol Dialog - Simplified */}
      <Dialog open={protocolDialog.open} onClose={() => setProtocolDialog({ open: false, mode: 'add', data: null })} maxWidth="md" fullWidth>
        <DialogTitle>
          {protocolDialog.mode === 'add' ? t('securityConfig.addProtocol') : t('securityConfig.editProtocol')}
        </DialogTitle>
        <DialogContent>
          <Alert severity="info" sx={{ mb: 2 }}>
            {t('securityConfig.protocolWarning')}
          </Alert>
          <TextField
            fullWidth
            margin="normal"
            label={t('securityConfig.name')}
            value={protocolDialog.data?.name || ''}
            onChange={(e) => setProtocolDialog({ ...protocolDialog, data: { ...protocolDialog.data, name: e.target.value } })}
          />
          <TextField
            fullWidth
            margin="normal"
            label={t('securityConfig.description')}
            multiline
            rows={2}
            value={protocolDialog.data?.description || ''}
            onChange={(e) => setProtocolDialog({ ...protocolDialog, data: { ...protocolDialog.data, description: e.target.value } })}
          />
          <Grid container spacing={2}>
            <Grid item xs={6}>
              <FormControl fullWidth margin="normal">
                <InputLabel>{t('securityConfig.severity')}</InputLabel>
                <Select
                  value={protocolDialog.data?.severity || 'high'}
                  onChange={(e) => setProtocolDialog({ ...protocolDialog, data: { ...protocolDialog.data, severity: e.target.value } })}
                >
                  <MenuItem value="low">Low</MenuItem>
                  <MenuItem value="medium">Medium</MenuItem>
                  <MenuItem value="high">High</MenuItem>
                  <MenuItem value="critical">Critical</MenuItem>
                </Select>
              </FormControl>
            </Grid>
            <Grid item xs={6}>
              <TextField
                fullWidth
                margin="normal"
                type="number"
                label={t('securityConfig.cooldownMinutes')}
                value={protocolDialog.data?.cooldown_minutes || 60}
                onChange={(e) => setProtocolDialog({ ...protocolDialog, data: { ...protocolDialog.data, cooldown_minutes: parseInt(e.target.value) } })}
              />
            </Grid>
          </Grid>
          <Box sx={{ mt: 2 }}>
            <FormControlLabel
              control={
                <Switch
                  checked={protocolDialog.data?.auto_execute || false}
                  onChange={(e) => setProtocolDialog({ ...protocolDialog, data: { ...protocolDialog.data, auto_execute: e.target.checked } })}
                />
              }
              label={t('securityConfig.autoExecute')}
            />
            <FormControlLabel
              control={
                <Switch
                  checked={protocolDialog.data?.enabled || false}
                  onChange={(e) => setProtocolDialog({ ...protocolDialog, data: { ...protocolDialog.data, enabled: e.target.checked } })}
                />
              }
              label={t('common.enabled')}
            />
          </Box>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setProtocolDialog({ open: false, mode: 'add', data: null })}>{t('common.cancel')}</Button>
          <Button variant="contained" onClick={handleSaveProtocol}>{t('common.save')}</Button>
        </DialogActions>
      </Dialog>

      {/* Delete Confirmation Dialog */}
      <Dialog open={deleteDialog.open} onClose={() => setDeleteDialog({ open: false, type: null, id: null })}>
        <DialogTitle>{t('common.confirmDelete')}</DialogTitle>
        <DialogContent>
          <Typography>{t('securityConfig.deleteWarning')}</Typography>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDeleteDialog({ open: false, type: null, id: null })}>{t('common.cancel')}</Button>
          <Button variant="contained" color="error" onClick={handleDelete}>{t('common.delete')}</Button>
        </DialogActions>
      </Dialog>
    </Container>
  );
};

export default SecurityConfigDashboard;
