import { useState, useEffect } from 'react';
import toast from 'react-hot-toast';
import {
  Box,
  Card,
  CardContent,
  Typography,
  Button,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
  Grid,
  Paper,
  Alert,
  CircularProgress,
  List,
  ListItem,
  ListItemText,
  Switch,
  FormControlLabel,
  Chip,
  IconButton,
  MenuItem,
  ListItemIcon,
} from '@mui/material';
import {
  Security as SecurityIcon,
  CheckCircle as CheckCircleIcon,
  Delete as DeleteIcon,
  ContentCopy as CopyIcon,
  Add as AddIcon,
  Webhook as WebhookIcon,
  PlayArrow as PlayIcon,
  Stop as StopIcon,
} from '@mui/icons-material';
import { QRCodeSVG } from 'qrcode.react';
import { useI18n } from '../contexts/I18nContext';
import { apiJson } from '../lib/api';
import { logger } from '../lib/logger';
import { formatDate } from '../lib/hooks';

interface MfaSetupResponse {
  method: string;
  secret: string;
  qr_code_url?: string;
  backup_codes: string[];
  test_code?: string;
}

const SettingsPage: React.FC = () => {
  const { t } = useI18n();
  const [activeTab] = useState<'profile' | 'security' | 'sync' | 'notifications'>('profile');

  // Profile state
  const [profile, setProfile] = useState({
    username: '',
    email: '',
    fullName: '',
    company: '',
  });
  const [profileLoading, setProfileLoading] = useState(true);
  const [profileSaving, setProfileSaving] = useState(false);
  const [profileSuccess, setProfileSuccess] = useState(false);

  // Sync state
  const [syncStatus, setSyncStatus] = useState({
    is_running: false,
    last_sync: null as string | null,
    next_sync: null as string | null,
  });
  const [syncLoading, setSyncLoading] = useState(true);

  // Notifications state
  const [webhooks, setWebhooks] = useState<{ id: number; url: string; event_type?: string }[]>([]);
  const [webhookUrl, setWebhookUrl] = useState('');
  const [webhookType, setWebhookType] = useState('sync_complete');
  const [webhookLoading, setWebhookLoading] = useState(false);
  const [emailNotifications, setEmailNotifications] = useState(false);
  const [webhookNotifications, setWebhookNotifications] = useState(false);
  const [notificationsLoading, setNotificationsLoading] = useState(true);
  
  // MFA state
  const [mfaSetupDialog, setMfaSetupDialog] = useState(false);
  const [, setMfaSecret] = useState('');
  const [mfaQrCode, setMfaQrCode] = useState<string | null>(null);
  const [mfaBackupCodes, setMfaBackupCodes] = useState<string[]>([]);
  const [mfaCodeInput, setMfaCodeInput] = useState('');
  const [mfaStep, setMfaStep] = useState<'setup' | 'verify' | 'success'>('setup');
  const [loading, setLoading] = useState(false);
  const [mfaEnabled, setMfaEnabled] = useState(false);
  
  // Password change
  const [currentPassword, setCurrentPassword] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [passwordError, setPasswordError] = useState('');
  const [passwordSuccess, setPasswordSuccess] = useState(false);

  const handleMfaSetup = async () => {
    setLoading(true);
    try {
      const data = await apiJson<MfaSetupResponse>('/auth/mfa/setup');
      setMfaSecret(data.secret);
      setMfaQrCode(data.qr_code_url || null);
      setMfaBackupCodes(data.backup_codes || []);
      setMfaSetupDialog(true);
    } catch (error) {
      logger.error('Failed to setup MFA:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleMfaVerify = async () => {
    setLoading(true);
    try {
      await apiJson('/auth/mfa/verify', {
        method: 'POST',
        body: JSON.stringify({ code: mfaCodeInput }),
      });
      setMfaStep('success');
      setMfaEnabled(true);
      setTimeout(() => {
        setMfaSetupDialog(false);
        setMfaStep('setup');
      }, 2000);
    } catch (error) {
      toast.error(t('settingsSecurity.mfaInvalidCode'));
      setMfaCodeInput('');
    } finally {
      setLoading(false);
    }
  };

  const handleMfaDisable = async () => {
    if (window.confirm(t('settingsSecurity.mfaConfirmDisable'))) {
      try {
        // Implement disable MFA endpoint
        setMfaEnabled(false);
      } catch (error) {
        logger.error('Failed to disable MFA:', error);
      }
    }
  };

  const handleChangePassword = async () => {
    if (newPassword !== confirmPassword) {
      setPasswordError(t('settingsSecurity.passwordMismatch'));
      return;
    }
    if (newPassword.length < 8) {
      setPasswordError(t('settingsSecurity.passwordTooShort'));
      return;
    }
    
    try {
      setPasswordError('');
      await apiJson('/auth/change-password', {
        method: 'POST',
        body: JSON.stringify({
          current_password: currentPassword,
          new_password: newPassword,
        }),
      });
      setPasswordSuccess(true);
      setCurrentPassword('');
      setNewPassword('');
      setConfirmPassword('');
      setTimeout(() => setPasswordSuccess(false), 3000);
    } catch (error: unknown) {
      setPasswordError(error instanceof Error ? error.message : 'Failed to change password');
    }
  };

  const copyToClipboard = (text: string) => {
    navigator.clipboard.writeText(text);
  };

  // Fetch profile data
  useEffect(() => {
    if (activeTab === 'profile') {
      fetchProfile();
    }
  }, [activeTab]);

  const fetchProfile = async () => {
    try {
      const data = await apiJson<{ username: string; email: string }>('/auth/me');
      setProfile({
        username: (data.username) || '',
        email: (data.email) || '',
        fullName: '',
        company: '',
      });
    } catch (error) {
      logger.error('Failed to fetch profile:', error);
    } finally {
      setProfileLoading(false);
    }
  };

  const handleSaveProfile = async () => {
    setProfileSaving(true);
    setProfileSuccess(false);
    try {
      await apiJson('/auth/me', {
        method: 'PUT',
        body: JSON.stringify(profile),
      });
      setProfileSuccess(true);
      setTimeout(() => setProfileSuccess(false), 3000);
    } catch (error: unknown) {
      toast.error(error instanceof Error ? error.message : 'Failed to save profile');
    } finally {
      setProfileSaving(false);
    }
  };

  // Fetch sync status
  useEffect(() => {
    if (activeTab === 'sync') {
      fetchSyncStatus();
    }
  }, [activeTab]);

  const fetchSyncStatus = async () => {
    try {
      const data = await apiJson<{ is_running: boolean; next_sync?: string }>('/sync/status');
      setSyncStatus({
        is_running: data.is_running || false,
        last_sync: null,
        next_sync: data.next_sync || null,
      });
    } catch (error) {
      logger.error('Failed to fetch sync status:', error);
    } finally {
      setSyncLoading(false);
    }
  };

  // Fetch notifications
  useEffect(() => {
    if (activeTab === 'notifications') {
      fetchNotifications();
    }
  }, [activeTab]);

  const fetchNotifications = async () => {
    try {
      const [webhooksData, configData] = await Promise.all([
        apiJson<{ id: number; url: string; event_type?: string }[]>('/webhooks'),
        apiJson<{ config: Record<string, unknown> }>('/config'),
      ]);

      setWebhooks(Array.isArray(webhooksData) ? webhooksData : []);
      setEmailNotifications((configData.config?.email_notifications as boolean) || false);
      setWebhookNotifications((configData.config?.webhook_notifications as boolean) || false);
    } catch (error) {
      logger.error('Failed to fetch notifications:', error);
    } finally {
      setNotificationsLoading(false);
    }
  };

  const handleAddWebhook = async () => {
    if (!webhookUrl) return;

    setWebhookLoading(true);
    try {
      await apiJson('/webhooks', {
        method: 'POST',
        body: JSON.stringify({ url: webhookUrl, event_type: webhookType }),
      });
      setWebhookUrl('');
      fetchNotifications();
    } catch (error: unknown) {
      toast.error(error instanceof Error ? error.message : 'Failed to add webhook');
    } finally {
      setWebhookLoading(false);
    }
  };

  const handleDeleteWebhook = async (id: number) => {
    if (!window.confirm(t('settingsNotifications.deleteConfirm'))) return;

    try {
      await apiJson(`/webhooks/${id}`, { method: 'DELETE' });
      fetchNotifications();
    } catch (error: unknown) {
      toast.error(error instanceof Error ? error.message : 'Failed to delete webhook');
    }
  };

  const handleSaveNotificationSettings = async () => {
    try {
      await apiJson('/config', {
        method: 'PUT',
        body: JSON.stringify({
          email_notifications: emailNotifications,
          webhook_notifications: webhookNotifications,
        }),
      });
      toast.success(t('settingsNotifications.success'));
    } catch (error: unknown) {
      toast.error(error instanceof Error ? error.message : 'Failed to save settings');
    }
  };

  return (
    <Box sx={{ flexGrow: 1 }}>
      <Typography variant="h4" gutterBottom>
        {t('settings.title')}
      </Typography>

      <Card>
        <CardContent>
          {activeTab === 'security' && (
            <Box>
              <Typography variant="h6" gutterBottom>
                {t('settingsSecurity.title')}
              </Typography>
              
              {/* MFA Section */}
              <Box sx={{ mb: 4 }}>
                <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
                  <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                    <SecurityIcon color={mfaEnabled ? 'success' : 'action'} />
                    <Typography variant="subtitle1">{t('settingsSecurity.mfa')}</Typography>
                  </Box>
                  {mfaEnabled ? (
                    <Button variant="outlined" color="error" onClick={handleMfaDisable}>
                      {t('settingsSecurity.disableMfa')}
                    </Button>
                  ) : (
                    <Button variant="contained" startIcon={<SecurityIcon />} onClick={handleMfaSetup}>
                      {t('settingsSecurity.enableMfa')}
                    </Button>
                  )}
                </Box>
                {mfaEnabled && (
                  <Alert severity="success">
                    {t('settingsSecurity.mfaEnabled')}
                  </Alert>
                )}
              </Box>

              <Box sx={{ borderBottom: 1, borderColor: 'divider', my: 3 }} />

              {/* Password Change Section */}
              <Box>
                <Typography variant="subtitle1" gutterBottom>
                  {t('settingsSecurity.changePassword')}
                </Typography>
                
                <Typography variant="body2" color="textSecondary" sx={{ mb: 2 }}>
                  {t('settingsSecurity.passwordHint')}
                </Typography>
                
                <Grid container spacing={2}>
                  <Grid item xs={12}>
                    <TextField
                      fullWidth
                      type="password"
                      label={t('settingsSecurity.currentPassword')}
                      value={currentPassword}
                      onChange={(e) => setCurrentPassword(e.target.value)}
                      disabled={passwordSuccess}
                    />
                  </Grid>
                  <Grid item xs={12}>
                    <TextField
                      fullWidth
                      type="password"
                      label={t('settingsSecurity.newPassword')}
                      value={newPassword}
                      onChange={(e) => setNewPassword(e.target.value)}
                      disabled={passwordSuccess}
                    />
                  </Grid>
                  <Grid item xs={12}>
                    <TextField
                      fullWidth
                      type="password"
                      label={t('settingsSecurity.confirmPassword')}
                      value={confirmPassword}
                      onChange={(e) => setConfirmPassword(e.target.value)}
                      disabled={passwordSuccess}
                    />
                  </Grid>
                </Grid>

                {passwordError && (
                  <Alert severity="error" sx={{ mt: 2 }}>
                    {passwordError}
                  </Alert>
                )}

                {passwordSuccess && (
                  <Alert severity="success" sx={{ mt: 2 }}>
                    {t('settingsSecurity.passwordChanged')}
                  </Alert>
                )}

                <Box sx={{ mt: 2 }}>
                  <Button
                    variant="contained"
                    onClick={handleChangePassword}
                    disabled={passwordSuccess}
                    sx={{ minWidth: 120 }}
                  >
                    {t('settingsSecurity.changePassword')}
                  </Button>
                </Box>
              </Box>
            </Box>
          )}

          {activeTab === 'profile' && (
            <Box>
              <Typography variant="h6" gutterBottom>
                {t('settingsProfile.title')}
              </Typography>

              {profileLoading ? (
                <Box display="flex" justifyContent="center" py={4}>
                  <CircularProgress />
                </Box>
              ) : (
                <Grid container spacing={3}>
                  <Grid item xs={12} md={6}>
                    <TextField
                      fullWidth
                      label={t('settingsProfile.username')}
                      value={profile.username}
                      disabled
                    />
                  </Grid>
                  <Grid item xs={12} md={6}>
                    <TextField
                      fullWidth
                      label={t('settingsProfile.email')}
                      value={profile.email}
                      disabled
                    />
                  </Grid>
                  <Grid item xs={12} md={6}>
                    <TextField
                      fullWidth
                      label={t('settingsProfile.fullName')}
                      value={profile.fullName}
                      onChange={(e) => setProfile({ ...profile, fullName: e.target.value })}
                    />
                  </Grid>
                  <Grid item xs={12} md={6}>
                    <TextField
                      fullWidth
                      label={t('settingsProfile.company')}
                      value={profile.company}
                      onChange={(e) => setProfile({ ...profile, company: e.target.value })}
                    />
                  </Grid>
                  <Grid item xs={12}>
                    <Button
                      variant="contained"
                      onClick={handleSaveProfile}
                      disabled={profileSaving}
                      sx={{ minWidth: 120 }}
                    >
                      {profileSaving ? t('common.save') : t('settingsProfile.save')}
                    </Button>
                    {profileSuccess && (
                      <Alert severity="success" sx={{ mt: 2 }}>
                        {t('settingsProfile.success')}
                      </Alert>
                    )}
                  </Grid>
                </Grid>
              )}
            </Box>
          )}

          {activeTab === 'sync' && (
            <Box>
              <Typography variant="h6" gutterBottom>
                {t('settingsSync.title')}
              </Typography>

              {syncLoading ? (
                <Box display="flex" justifyContent="center" py={4}>
                  <CircularProgress />
                </Box>
              ) : (
                <Grid container spacing={3}>
                  <Grid item xs={12}>
                    <Card variant="outlined">
                      <CardContent>
                        <Box display="flex" alignItems="center" justifyContent="space-between">
                          <Box display="flex" alignItems="center">
                            {syncStatus.is_running && (
                              <Box display="flex" alignItems="center" mr={2}>
                                <CircularProgress size={20} sx={{ mr: 1 }} />
                                <Typography>{t('sync.running')}</Typography>
                              </Box>
                            )}
                            <Chip
                              label={syncStatus.is_running ? t('sync.running') : t('sync.idle')}
                              color={syncStatus.is_running ? 'primary' : 'default'}
                            />
                          </Box>
                          <Box>
                            <Button
                              variant="contained"
                              color="primary"
                              startIcon={<PlayIcon />}
                              onClick={() => { /* TODO: Start sync */ }}
                              disabled={syncStatus.is_running}
                              sx={{ mr: 1 }}
                            >
                              {t('sync.startSync')}
                            </Button>
                            <Button
                              variant="contained"
                              color="error"
                              startIcon={<StopIcon />}
                              onClick={() => { /* TODO: Stop sync */ }}
                              disabled={!syncStatus.is_running}
                              sx={{ mr: 1 }}
                            >
                              {t('sync.stopSync')}
                            </Button>
                          </Box>
                        </Box>
                      </CardContent>
                    </Card>
                  </Grid>

                  <Grid item xs={12}>
                    <Card variant="outlined">
                      <CardContent>
                        <Typography variant="subtitle1" gutterBottom>
                          {t('settingsSync.status')}
                        </Typography>
                        <Grid container spacing={2}>
                          <Grid item xs={6}>
                            <Typography variant="body2" color="textSecondary">
                              {t('settingsSync.lastSync')}
                            </Typography>
                            <Typography variant="body1">
                              {syncStatus.last_sync ? formatDate(syncStatus.last_sync) : '-'}
                            </Typography>
                          </Grid>
                          <Grid item xs={6}>
                            <Typography variant="body2" color="textSecondary">
                              {t('settingsSync.nextSync')}
                            </Typography>
                            <Typography variant="body1">
                              {syncStatus.next_sync ? formatDate(syncStatus.next_sync) : '-'}
                            </Typography>
                          </Grid>
                        </Grid>
                      </CardContent>
                    </Card>
                  </Grid>
                </Grid>
              )}
            </Box>
          )}

          {activeTab === 'notifications' && (
            <Box>
              <Typography variant="h6" gutterBottom>
                {t('settingsNotifications.title')}
              </Typography>

              {notificationsLoading ? (
                <Box display="flex" justifyContent="center" py={4}>
                  <CircularProgress />
                </Box>
              ) : (
                <Grid container spacing={3}>
                  <Grid item xs={12}>
                    <Card variant="outlined">
                      <CardContent>
                        <Typography variant="subtitle1" gutterBottom>
                          {t('settingsNotifications.emailNotifications')}
                        </Typography>
                        <Typography variant="body2" color="textSecondary" sx={{ mb: 2 }}>
                          {t('settingsNotifications.emailNotificationsDesc')}
                        </Typography>
                        <FormControlLabel
                          control={
                            <Switch
                              checked={emailNotifications}
                              onChange={(e) => setEmailNotifications(e.target.checked)}
                            />
                          }
                          label={t('settingsNotifications.emailNotifications')}
                        />
                      </CardContent>
                    </Card>
                  </Grid>

                  <Grid item xs={12}>
                    <Card variant="outlined">
                      <CardContent>
                        <Typography variant="subtitle1" gutterBottom>
                          {t('settingsNotifications.webhookNotifications')}
                        </Typography>
                        <Typography variant="body2" color="textSecondary" sx={{ mb: 2 }}>
                          {t('settingsNotifications.webhookNotificationsDesc')}
                        </Typography>
                        <FormControlLabel
                          control={
                            <Switch
                              checked={webhookNotifications}
                              onChange={(e) => setWebhookNotifications(e.target.checked)}
                            />
                          }
                          label={t('settingsNotifications.webhookNotifications')}
                        />
                      </CardContent>
                    </Card>
                  </Grid>

                  <Grid item xs={12}>
                    <Card variant="outlined">
                      <CardContent>
                        <Typography variant="subtitle1" gutterBottom>
                          {t('settingsNotifications.webhooks')}
                        </Typography>

                        <Box sx={{ mb: 3 }}>
                          <Grid container spacing={2}>
                            <Grid item xs={12} md={5}>
                              <TextField
                                fullWidth
                                label={t('settingsNotifications.webhookUrl')}
                                value={webhookUrl}
                                onChange={(e) => setWebhookUrl(e.target.value)}
                                placeholder="https://example.com/webhook"
                              />
                            </Grid>
                            <Grid item xs={12} md={3}>
                              <TextField
                                fullWidth
                                label={t('settingsNotifications.webhookType')}
                                value={webhookType}
                                onChange={(e) => setWebhookType(e.target.value)}
                                select
                              >
                                <MenuItem value="sync_complete">Sync Complete</MenuItem>
                                <MenuItem value="sync_failed">Sync Failed</MenuItem>
                                <MenuItem value="alert_triggered">Alert Triggered</MenuItem>
                              </TextField>
                            </Grid>
                            <Grid item xs={12} md={4}>
                              <Button
                                fullWidth
                                variant="contained"
                                startIcon={<AddIcon />}
                                onClick={handleAddWebhook}
                                disabled={webhookLoading || !webhookUrl}
                              >
                                {t('settingsNotifications.addWebhook')}
                              </Button>
                            </Grid>
                          </Grid>
                        </Box>

                        <List>
                          {webhooks.length === 0 ? (
                            <Typography variant="body2" color="textSecondary">
                              {t('settingsNotifications.noWebhooks')}
                            </Typography>
                          ) : (
                            webhooks.map((webhook) => (
                              <ListItem
                                key={webhook.id}
                                secondaryAction={
                                  <IconButton
                                    edge="end"
                                    onClick={() => handleDeleteWebhook(webhook.id)}
                                  >
                                    <DeleteIcon />
                                  </IconButton>
                                }
                              >
                                <ListItemIcon>
                                  <WebhookIcon color="primary" />
                                </ListItemIcon>
                                <ListItemText
                                  primary={webhook.url}
                                  secondary={webhook.event_type}
                                />
                              </ListItem>
                            ))
                          )}
                        </List>
                      </CardContent>
                    </Card>
                  </Grid>

                  <Grid item xs={12}>
                    <Button
                      variant="contained"
                      onClick={handleSaveNotificationSettings}
                    >
                      {t('settingsNotifications.save')}
                    </Button>
                  </Grid>
                </Grid>
              )}
            </Box>
          )}
        </CardContent>
      </Card>

      {/* MFA Setup Dialog */}
      <Dialog open={mfaSetupDialog} onClose={() => setMfaSetupDialog(false)} maxWidth="md" fullWidth>
        <DialogTitle>
          {mfaStep === 'setup' && t('settingsSecurity.mfaSetupTitle')}
          {mfaStep === 'verify' && t('settingsSecurity.mfaVerifyTitle')}
          {mfaStep === 'success' && t('settingsSecurity.mfaSuccessTitle')}
        </DialogTitle>
        <DialogContent dividers>
          {loading && <CircularProgress sx={{ mb: 2 }} />}
          
          {mfaStep === 'setup' && (
            <Box>
              <Typography variant="body1" paragraph>
                {t('settingsSecurity.mfaSteps')}
              </Typography>
              
              <Box sx={{ mb: 3 }}>
                <Typography variant="subtitle2" gutterBottom>{t('settingsSecurity.mfaStep1')}</Typography>
                <Paper variant="outlined" sx={{ p: 2, textAlign: 'center' }}>
                  {mfaQrCode && <QRCodeSVG value={mfaQrCode} size={200} />}
                  <Typography variant="caption" color="textSecondary" sx={{ mt: 1, display: 'block' }}>
                    {t('settingsSecurity.mfaScanHint')}
                  </Typography>
                </Paper>
              </Box>

              <Box sx={{ mb: 3 }}>
                <Typography variant="subtitle2" gutterBottom>{t('settingsSecurity.mfaStep2')}</Typography>
                <Alert severity="warning">
                  {t('settingsSecurity.mfaBackupWarning')}
                </Alert>
                <List sx={{ mt: 1, bgcolor: '#f5f5f5', p: 2, borderRadius: 1, maxHeight: 200, overflow: 'auto' }}>
                  {mfaBackupCodes.map((code, index) => (
                    <ListItem key={index}>
                      <ListItemText
                        primary={
                          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                            <Typography variant="body2" fontWeight={600}>{code}</Typography>
                            <Button
                              size="small"
                              onClick={() => copyToClipboard(code)}
                              startIcon={<CopyIcon fontSize="small" />}
                            >
                              {t('settingsSecurity.copy')}
                            </Button>
                          </Box>
                        }
                      />
                    </ListItem>
                  ))}
                </List>
              </Box>

              <Box sx={{ mb: 3 }}>
                <Typography variant="subtitle2" gutterBottom>{t('settingsSecurity.mfaStep3')}</Typography>
                <TextField
                  fullWidth
                  variant="outlined"
                  label={t('settingsSecurity.verificationCode')}
                  value={mfaCodeInput}
                  onChange={(e) => setMfaCodeInput(e.target.value.replace(/\D/g, '').slice(0, 6))}
                  placeholder="000 000"
                  margin="normal"
                  InputLabelProps={{ shrink: true }}
                />
              </Box>

              <Box sx={{ mt: 2, textAlign: 'center', mb: 0 }}>
                <Button
                  variant="contained"
                  size="large"
                  disabled={mfaCodeInput.length !== 6}
                  onClick={() => setMfaStep('verify')}
                >
                  {t('settingsSecurity.continueVerify')}
                </Button>
              </Box>
            </Box>
          )}

          {mfaStep === 'verify' && (
            <Box sx={{ p: 2 }}>
              <Button
                variant="contained"
                size="large"
                disabled={loading}
                onClick={handleMfaVerify}
                fullWidth
              >
                {t('settingsSecurity.verifyEnable')}
              </Button>
              <Box sx={{ mt: 1, textAlign: 'center' }}>
                <Button onClick={() => setMfaStep('setup')} size="small">
                  Back
                </Button>
              </Box>
            </Box>
          )}

          {mfaStep === 'success' && (
            <Box sx={{ p: 3, textAlign: 'center' }}>
              <CheckCircleIcon color="success" sx={{ fontSize: 80, mb: 2 }} />
              <Typography variant="h6" paragraph>
                {t('settingsSecurity.mfaSuccess')}
              </Typography>
              <Typography variant="body2" color="textSecondary">
                {t('settingsSecurity.mfaSuccessHint')}
              </Typography>
            </Box>
          )}
        </DialogContent>
        {mfaStep !== 'success' && (
          <DialogActions>
            <Button onClick={() => setMfaSetupDialog(false)}>{t('common.cancel')}</Button>
          </DialogActions>
        )}
      </Dialog>
    </Box>
  );
};

export default SettingsPage;
