import React, { useState, useEffect } from 'react';
import {
  Box,
  Card,
  CardContent,
  Typography,
  Switch,
  FormControlLabel,
  Button,
  Divider,
  Alert,
  Chip,
  List,
  ListItem,
  ListItemText,
  ListItemIcon,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  CircularProgress
} from '@mui/material';
import {
  Security,
  Shield,
  Lock,
  VpnKey,
  DevicesOther,
  Warning,
  CheckCircle,
  Info
} from '@mui/icons-material';
import { useTranslation } from 'react-i18next';
import { useAuthStore } from '../store/authStore';
import { useSecurityNotification } from './SecurityNotificationProvider';
import axios from 'axios';

const SecuritySettingsPanel = () => {
  const { t } = useTranslation();
  const { token, user } = useAuthStore();
  const { notifySecuritySuccess, notifySecurityError } = useSecurityNotification();
  const [loading, setLoading] = useState(true);
  const [settings, setSettings] = useState({
    twoFactorEnabled: false,
    sessionTimeout: 7 * 24 * 60, // minutes
    passwordExpiryDays: 90,
    requireStrongPassword: true,
    accountLockoutEnabled: true,
    maxFailedAttempts: 5,
    lockoutDuration: 30 // minutes
  });
  const [sessions, setSessions] = useState([]);
  const [showTerminateDialog, setShowTerminateDialog] = useState(false);

  useEffect(() => {
    fetchSecuritySettings();
    fetchActiveSessions();
  }, []);

  const fetchSecuritySettings = async () => {
    try {
      const response = await axios.get('/api/auth/security-status', {
        headers: { Authorization: `Bearer ${token}` }
      });
      
      if (response.data) {
        setSettings(prev => ({
          ...prev,
          twoFactorEnabled: response.data.twoFactorEnabled || false
        }));
      }
    } catch (error) {
      console.error('Error fetching security settings:', error);
    } finally {
      setLoading(false);
    }
  };

  const fetchActiveSessions = async () => {
    try {
      const response = await axios.get('/api/auth/sessions', {
        headers: { Authorization: `Bearer ${token}` }
      });
      
      if (response.data) {
        setSessions(response.data);
      }
    } catch (error) {
      console.error('Error fetching sessions:', error);
    }
  };

  const handleTerminateAllSessions = async () => {
    try {
      await axios.post('/api/auth/sessions/terminate-all', {}, {
        headers: { Authorization: `Bearer ${token}` }
      });
      
      notifySecuritySuccess(t('security.terminateAllSessions'));
      setShowTerminateDialog(false);
      fetchActiveSessions();
    } catch (error) {
      notifySecurityError(t('error'), error.response?.data?.error);
    }
  };

  if (loading) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', p: 4 }}>
        <CircularProgress />
      </Box>
    );
  }

  return (
    <Box>
      <Typography variant="h5" sx={{ mb: 3, display: 'flex', alignItems: 'center', gap: 1 }}>
        <Security color="primary" />
        {t('security.title')}
      </Typography>

      {/* Security Status Overview */}
      <Card sx={{ mb: 3 }}>
        <CardContent>
          <Typography variant="h6" sx={{ mb: 2, display: 'flex', alignItems: 'center', gap: 1 }}>
            <Shield color="primary" />
            {t('security.securityStatus')}
          </Typography>
          
          <List>
            <ListItem>
              <ListItemIcon>
                {settings.twoFactorEnabled ? (
                  <CheckCircle color="success" />
                ) : (
                  <Warning color="warning" />
                )}
              </ListItemIcon>
              <ListItemText
                primary={t('twoFactor.title')}
                secondary={
                  settings.twoFactorEnabled
                    ? t('security.twoFactorEnabled')
                    : t('twoFactor.notEnabled')
                }
              />
              <Chip
                label={settings.twoFactorEnabled ? t('enabled') : t('disabled')}
                color={settings.twoFactorEnabled ? 'success' : 'default'}
                size="small"
              />
            </ListItem>

            <ListItem>
              <ListItemIcon>
                {settings.requireStrongPassword ? (
                  <CheckCircle color="success" />
                ) : (
                  <Info color="info" />
                )}
              </ListItemIcon>
              <ListItemText
                primary={t('security.passwordPolicy')}
                secondary={t('security.minLength')}
              />
              <Chip
                label={settings.requireStrongPassword ? t('enabled') : t('disabled')}
                color={settings.requireStrongPassword ? 'success' : 'default'}
                size="small"
              />
            </ListItem>

            <ListItem>
              <ListItemIcon>
                {settings.accountLockoutEnabled ? (
                  <CheckCircle color="success" />
                ) : (
                  <Info color="info" />
                )}
              </ListItemIcon>
              <ListItemText
                primary={t('security.accountLockout')}
                secondary={`${settings.maxFailedAttempts} ${t('security.failedAttempts')}`}
              />
              <Chip
                label={settings.accountLockoutEnabled ? t('enabled') : t('disabled')}
                color={settings.accountLockoutEnabled ? 'success' : 'default'}
                size="small"
              />
            </ListItem>
          </List>
        </CardContent>
      </Card>

      {/* Active Sessions */}
      <Card sx={{ mb: 3 }}>
        <CardContent>
          <Typography variant="h6" sx={{ mb: 2, display: 'flex', alignItems: 'center', gap: 1 }}>
            <DevicesOther color="primary" />
            {t('security.activeSessions')}
          </Typography>

          {sessions.length > 0 ? (
            <>
              <Alert severity="info" sx={{ mb: 2 }}>
                {t('security.multipleDevices', { count: sessions.length })}
              </Alert>
              
              <List>
                {sessions.map((session, index) => (
                  <ListItem key={index}>
                    <ListItemText
                      primary={session.device || 'Unknown Device'}
                      secondary={`Last active: ${new Date(session.lastActive).toLocaleString()}`}
                    />
                    {session.current && (
                      <Chip label="Current" color="primary" size="small" />
                    )}
                  </ListItem>
                ))}
              </List>

              {sessions.length > 1 && (
                <Button
                  variant="outlined"
                  color="error"
                  onClick={() => setShowTerminateDialog(true)}
                  sx={{ mt: 2 }}
                >
                  {t('security.terminateAllSessions')}
                </Button>
              )}
            </>
          ) : (
            <Typography variant="body2" color="text.secondary">
              {t('security.noRecentActivity')}
            </Typography>
          )}
        </CardContent>
      </Card>

      {/* Input Validation Info */}
      <Card>
        <CardContent>
          <Typography variant="h6" sx={{ mb: 2, display: 'flex', alignItems: 'center', gap: 1 }}>
            <VpnKey color="primary" />
            {t('security.inputValidation')}
          </Typography>

          <Alert severity="info" sx={{ mb: 2 }}>
            {t('security.inputSanitized')}
          </Alert>

          <List dense>
            <ListItem>
              <ListItemIcon>
                <CheckCircle color="success" fontSize="small" />
              </ListItemIcon>
              <ListItemText primary={t('security.xssAttemptBlocked')} />
            </ListItem>
            <ListItem>
              <ListItemIcon>
                <CheckCircle color="success" fontSize="small" />
              </ListItemIcon>
              <ListItemText primary={t('security.sqlInjectionBlocked')} />
            </ListItem>
            <ListItem>
              <ListItemIcon>
                <CheckCircle color="success" fontSize="small" />
              </ListItemIcon>
              <ListItemText primary={t('security.rateLimitExceeded').split('.')[0]} />
            </ListItem>
          </List>
        </CardContent>
      </Card>

      {/* Terminate Sessions Dialog */}
      <Dialog open={showTerminateDialog} onClose={() => setShowTerminateDialog(false)}>
        <DialogTitle>{t('security.terminateAllSessions')}</DialogTitle>
        <DialogContent>
          <Alert severity="warning" sx={{ mb: 2 }}>
            {t('security.sessionExpired')}
          </Alert>
          <Typography>
            This will log you out from all other devices. Your current session will remain active.
          </Typography>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setShowTerminateDialog(false)}>
            {t('cancel')}
          </Button>
          <Button onClick={handleTerminateAllSessions} color="error" variant="contained">
            {t('security.terminateAllSessions')}
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default SecuritySettingsPanel;
