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
} from '@mui/material';
import {
  Security,
  Lock,
  Warning,
  CheckCircle,
  ErrorOutline,
  Refresh,
  LockOpen,
  AdminPanelSettings,
  BugReport,
  Settings
} 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 SecurityDashboard = () => {
  const { t } = useTranslation();
  const { token, user } = useAuthStore();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [tabValue, setTabValue] = useState(0);
  const [securityData, setSecurityData] = useState({
    lockedAccounts: [],
    recentFailures: [],
    securityEvents: [],
    stats: {
      totalUsers: 0,
      lockedAccounts: 0,
      failedAttempts24h: 0,
      passwordChanges24h: 0
    }
  });
  const [auditLog, setAuditLog] = useState([]);
  const [auditLoading, setAuditLoading] = useState(false);

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

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

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

  const fetchSecurityData = async () => {
    setLoading(true);
    setError('');
    try {
      // Fetch user data
      const usersResponse = await axios.get('/api/users', {
        headers: { Authorization: `Bearer ${token}` }
      });

      // Fetch security status from new monitoring API
      const statusResponse = await axios.get('/api/security-monitor/status', {
        headers: { Authorization: `Bearer ${token}` }
      }).catch(() => null);

      const users = usersResponse.data;
      const lockedUsers = users.filter(u => u.locked_until && new Date(u.locked_until) > new Date());
      const usersWithFailures = users.filter(u => u.failed_login_attempts > 0);

      // Get password changes from audit log if available
      let passwordChanges24h = 0;
      if (statusResponse?.data?.systemHealth) {
        passwordChanges24h = statusResponse.data.systemHealth.passwordChanges || 0;
      }

      setSecurityData({
        lockedAccounts: lockedUsers,
        recentFailures: usersWithFailures,
        securityEvents: statusResponse?.data?.auditSummary || [],
        stats: {
          totalUsers: users.length,
          lockedAccounts: lockedUsers.length,
          failedAttempts24h: usersWithFailures.reduce((sum, u) => sum + u.failed_login_attempts, 0),
          passwordChanges24h
        }
      });
    } catch (err) {
      // Only show error if not authentication related
      if (err.response?.status !== 401) {
        setError(err.response?.data?.error || 'Failed to load security data');
      }
    } finally {
      setLoading(false);
    }
  };

  const fetchAuditLog = async () => {
    setAuditLoading(true);
    try {
      const response = await axios.get('/api/security-monitor/audit-log?limit=50', {
        headers: { Authorization: `Bearer ${token}` }
      });
      setAuditLog(response.data.logs || []);
    } catch (err) {
      // Silently fail for authentication errors
      if (err.response?.status !== 401) {
        console.error('Error fetching audit log:', err);
      }
      setAuditLog([]);
    } finally {
      setAuditLoading(false);
    }
  };

  const handleUnlockAccount = async (userId) => {
    try {
      await axios.post(`/api/users/${userId}/unlock`, {}, {
        headers: { Authorization: `Bearer ${token}` }
      });
      fetchSecurityData();
    } catch (err) {
      setError('Failed to unlock account');
    }
  };

  if (user?.role !== 'admin') {
    return null;
  }

  return (
    <Container maxWidth="xl">
      <Box sx={{ py: 3 }}>
        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
            <Security color="primary" fontSize="large" />
            <Typography variant="h4" fontWeight="bold">
              {t('security.securityDashboard')}
            </Typography>
          </Box>
          <IconButton onClick={fetchSecurityData} disabled={loading}>
            <Refresh />
          </IconButton>
        </Box>

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

        {/* Quick Links */}
        <Grid container spacing={2} sx={{ mb: 3 }}>
          <Grid item xs={12} md={3}>
            <Button
              fullWidth
              variant="outlined"
              startIcon={<Security />}
              onClick={() => navigate('/security/monitor')}
              sx={{ py: 1.5 }}
            >
              {t('security.monitoring')}
            </Button>
          </Grid>
          <Grid item xs={12} md={3}>
            <Button
              fullWidth
              variant="outlined"
              startIcon={<Lock />}
              onClick={() => navigate('/security/headers')}
              sx={{ py: 1.5 }}
            >
              {t('security.securityHeaders')}
            </Button>
          </Grid>
          <Grid item xs={12} md={3}>
            <Button
              fullWidth
              variant="outlined"
              startIcon={<Security />}
              onClick={() => navigate('/security/csp')}
              sx={{ py: 1.5 }}
            >
              {t('security.cspDashboard')}
            </Button>
          </Grid>
          <Grid item xs={12} md={3}>
            <Button
              fullWidth
              variant="outlined"
              startIcon={<AdminPanelSettings />}
              onClick={() => navigate('/security/rbac')}
              sx={{ py: 1.5 }}
            >
              {t('security.rbacDashboard')}
            </Button>
          </Grid>
          <Grid item xs={12} md={3}>
            <Button
              fullWidth
              variant="contained"
              color="primary"
              startIcon={<BugReport />}
              onClick={() => navigate('/security/testing')}
              sx={{ py: 1.5 }}
            >
              {t('security.securityTesting')}
            </Button>
          </Grid>
          <Grid item xs={12} md={3}>
            <Button
              fullWidth
              variant="contained"
              color="success"
              startIcon={<Security />}
              onClick={() => navigate('/security/intelligence')}
              sx={{ py: 1.5 }}
            >
              {t('siem.title')}
            </Button>
          </Grid>
          <Grid item xs={12} md={3}>
            <Button
              fullWidth
              variant="contained"
              color="warning"
              startIcon={<Settings />}
              onClick={() => navigate('/security/config')}
              sx={{ py: 1.5 }}
            >
              {t('securityConfig.title')}
            </Button>
          </Grid>
          <Grid item xs={12} md={3}>
            <Button
              fullWidth
              variant="contained"
              color="info"
              startIcon={<AdminPanelSettings />}
              onClick={() => navigate('/security/logs')}
              sx={{ py: 1.5 }}
            >
              {t('logManagement.title')}
            </Button>
          </Grid>
          <Grid item xs={12} md={3}>
            <Button
              fullWidth
              variant="contained"
              color="secondary"
              startIcon={<Lock />}
              onClick={() => navigate('/security/encryption')}
              sx={{ py: 1.5 }}
            >
              {t('encryption.title')}
            </Button>
          </Grid>
        </Grid>

        {/* Stats Cards */}
        <Grid container spacing={3} sx={{ mb: 3 }}>
          <Grid item xs={12} sm={6} md={3}>
            <Card>
              <CardContent>
                <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                  <Box>
                    <Typography variant="caption" color="text.secondary">
                      {t('security.allUsers')}
                    </Typography>
                    <Typography variant="h4" fontWeight="bold">
                      {securityData.stats.totalUsers}
                    </Typography>
                  </Box>
                  <CheckCircle sx={{ fontSize: 48, color: 'success.main', opacity: 0.3 }} />
                </Box>
              </CardContent>
            </Card>
          </Grid>

          <Grid item xs={12} sm={6} md={3}>
            <Card>
              <CardContent>
                <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                  <Box>
                    <Typography variant="caption" color="text.secondary">
                      {t('security.lockedAccounts')}
                    </Typography>
                    <Typography variant="h4" fontWeight="bold" color="error.main">
                      {securityData.stats.lockedAccounts}
                    </Typography>
                  </Box>
                  <Lock sx={{ fontSize: 48, color: 'error.main', opacity: 0.3 }} />
                </Box>
              </CardContent>
            </Card>
          </Grid>

          <Grid item xs={12} sm={6} md={3}>
            <Card>
              <CardContent>
                <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                  <Box>
                    <Typography variant="caption" color="text.secondary">
                      {t('security.recentFailures')} (24h)
                    </Typography>
                    <Typography variant="h4" fontWeight="bold" color="warning.main">
                      {securityData.stats.failedAttempts24h}
                    </Typography>
                  </Box>
                  <Warning sx={{ fontSize: 48, color: 'warning.main', opacity: 0.3 }} />
                </Box>
              </CardContent>
            </Card>
          </Grid>

          <Grid item xs={12} sm={6} md={3}>
            <Card>
              <CardContent>
                <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                  <Box>
                    <Typography variant="caption" color="text.secondary">
                      {t('security.passwordChange')} (24h)
                    </Typography>
                    <Typography variant="h4" fontWeight="bold" color="info.main">
                      {securityData.stats.passwordChanges24h}
                    </Typography>
                  </Box>
                  <Security sx={{ fontSize: 48, color: 'info.main', opacity: 0.3 }} />
                </Box>
              </CardContent>
            </Card>
          </Grid>
        </Grid>

        {/* Tabs */}
        <Paper>
          <Tabs value={tabValue} onChange={(e, v) => setTabValue(v)} sx={{ borderBottom: 1, borderColor: 'divider' }}>
            <Tab label={t('security.lockedAccounts')} icon={<Lock />} iconPosition="start" />
            <Tab label={t('security.recentFailures')} icon={<Warning />} iconPosition="start" />
            <Tab label={t('security.auditLog')} icon={<Security />} iconPosition="start" />
          </Tabs>

          {loading ? (
            <Box sx={{ display: 'flex', justifyContent: 'center', p: 4 }}>
              <CircularProgress />
            </Box>
          ) : (
            <>
              {/* Locked Accounts Tab */}
              <TabPanel value={tabValue} index={0}>
                {securityData.lockedAccounts.length === 0 ? (
                  <Box sx={{ textAlign: 'center', py: 4 }}>
                    <CheckCircle sx={{ fontSize: 64, color: 'success.main', mb: 2 }} />
                    <Typography variant="body1" color="text.secondary">
                      No locked accounts
                    </Typography>
                  </Box>
                ) : (
                  <TableContainer>
                    <Table>
                      <TableHead>
                        <TableRow>
                          <TableCell>{t('settings.username')}</TableCell>
                          <TableCell>{t('settings.email')}</TableCell>
                          <TableCell>{t('security.failedAttempts')}</TableCell>
                          <TableCell>{t('security.accountLocked')}</TableCell>
                          <TableCell>{t('settings.actions')}</TableCell>
                        </TableRow>
                      </TableHead>
                      <TableBody>
                        {securityData.lockedAccounts.map((user) => (
                          <TableRow key={user.id}>
                            <TableCell>{user.username}</TableCell>
                            <TableCell>{user.email}</TableCell>
                            <TableCell>
                              <Chip
                                label={user.failed_login_attempts || 0}
                                color="error"
                                size="small"
                              />
                            </TableCell>
                            <TableCell>
                              {user.locked_until ? format(new Date(user.locked_until), 'PPpp') : '-'}
                            </TableCell>
                            <TableCell>
                              <Button
                                size="small"
                                startIcon={<LockOpen />}
                                onClick={() => handleUnlockAccount(user.id)}
                              >
                                {t('security.unlockAccount')}
                              </Button>
                            </TableCell>
                          </TableRow>
                        ))}
                      </TableBody>
                    </Table>
                  </TableContainer>
                )}
              </TabPanel>

              {/* Recent Failures Tab */}
              <TabPanel value={tabValue} index={1}>
                {securityData.recentFailures.length === 0 ? (
                  <Box sx={{ textAlign: 'center', py: 4 }}>
                    <CheckCircle sx={{ fontSize: 64, color: 'success.main', mb: 2 }} />
                    <Typography variant="body1" color="text.secondary">
                      No recent failed attempts
                    </Typography>
                  </Box>
                ) : (
                  <TableContainer>
                    <Table>
                      <TableHead>
                        <TableRow>
                          <TableCell>{t('settings.username')}</TableCell>
                          <TableCell>{t('settings.email')}</TableCell>
                          <TableCell>{t('security.failedAttempts')}</TableCell>
                          <TableCell>{t('security.lastLogin')}</TableCell>
                          <TableCell>{t('settings.status')}</TableCell>
                        </TableRow>
                      </TableHead>
                      <TableBody>
                        {securityData.recentFailures.map((user) => (
                          <TableRow key={user.id}>
                            <TableCell>{user.username}</TableCell>
                            <TableCell>{user.email}</TableCell>
                            <TableCell>
                              <Chip
                                label={user.failed_login_attempts || 0}
                                color={user.failed_login_attempts >= 3 ? 'error' : 'warning'}
                                size="small"
                              />
                            </TableCell>
                            <TableCell>
                              {user.last_failed_login ? format(new Date(user.last_failed_login), 'PPpp') : '-'}
                            </TableCell>
                            <TableCell>
                              <Chip
                                label={user.locked_until && new Date(user.locked_until) > new Date() ? 'Locked' : 'Active'}
                                color={user.locked_until && new Date(user.locked_until) > new Date() ? 'error' : 'success'}
                                size="small"
                              />
                            </TableCell>
                          </TableRow>
                        ))}
                      </TableBody>
                    </Table>
                  </TableContainer>
                )}
              </TabPanel>

              {/* Audit Log Tab */}
              <TabPanel value={tabValue} index={2}>
                {auditLoading ? (
                  <Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}>
                    <CircularProgress />
                  </Box>
                ) : auditLog.length === 0 ? (
                  <Box sx={{ textAlign: 'center', py: 4 }}>
                    <Security sx={{ fontSize: 64, color: 'text.secondary', mb: 2 }} />
                    <Typography variant="body1" color="text.secondary" gutterBottom>
                      {t('security.noEvents')}
                    </Typography>
                    <Button
                      variant="outlined"
                      startIcon={<Refresh />}
                      onClick={fetchAuditLog}
                      sx={{ mt: 2 }}
                    >
                      {t('refresh')}
                    </Button>
                  </Box>
                ) : (
                  <>
                    <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', p: 2 }}>
                      <Typography variant="h6">
                        {t('security.recentEvents')} ({auditLog.length})
                      </Typography>
                      <Button
                        variant="outlined"
                        size="small"
                        onClick={() => navigate('/security/monitor')}
                      >
                        {t('security.viewDetails')}
                      </Button>
                    </Box>
                    <TableContainer>
                      <Table>
                        <TableHead>
                          <TableRow>
                            <TableCell>{t('security.timestamp')}</TableCell>
                            <TableCell>{t('security.eventType')}</TableCell>
                            <TableCell>{t('security.status')}</TableCell>
                            <TableCell>{t('security.ipAddress')}</TableCell>
                            <TableCell>{t('details')}</TableCell>
                          </TableRow>
                        </TableHead>
                        <TableBody>
                          {auditLog.slice(0, 20).map((log) => (
                            <TableRow key={log.id}>
                              <TableCell>
                                {format(new Date(log.timestamp), 'MMM dd, HH:mm:ss')}
                              </TableCell>
                              <TableCell>
                                <Chip
                                  label={log.action}
                                  size="small"
                                  variant="outlined"
                                />
                              </TableCell>
                              <TableCell>
                                <Chip
                                  label={log.result}
                                  color={
                                    log.result === 'success' ? 'success' :
                                    log.result === 'failed' ? 'error' :
                                    'warning'
                                  }
                                  size="small"
                                />
                              </TableCell>
                              <TableCell>
                                <Typography variant="body2" sx={{ fontFamily: 'monospace', fontSize: '0.75rem' }}>
                                  {log.ip_address || '-'}
                                </Typography>
                              </TableCell>
                              <TableCell>
                                {log.details && (
                                  <Typography variant="caption" color="text.secondary">
                                    {JSON.parse(log.details).username || 
                                     JSON.parse(log.details).reason ||
                                     'See details'}
                                  </Typography>
                                )}
                              </TableCell>
                            </TableRow>
                          ))}
                        </TableBody>
                      </Table>
                    </TableContainer>
                    <Box sx={{ p: 2, textAlign: 'center' }}>
                      <Button
                        variant="text"
                        onClick={() => navigate('/security/monitor')}
                      >
                        {t('security.viewDetails')} →
                      </Button>
                    </Box>
                  </>
                )}
              </TabPanel>
            </>
          )}
        </Paper>
      </Box>
    </Container>
  );
};

export default SecurityDashboard;
