import React, { useState, useEffect } from 'react';
import {
  Card,
  CardContent,
  Typography,
  Box,
  Chip,
  CircularProgress,
  Alert,
  List,
  ListItem,
  ListItemIcon,
  ListItemText,
  Divider,
  IconButton,
  Collapse
} from '@mui/material';
import {
  Security,
  CheckCircle,
  Warning,
  Error as ErrorIcon,
  ExpandMore,
  Shield,
  Key,
  Devices,
  History
} from '@mui/icons-material';
import { useTranslation } from 'react-i18next';
import { useAuthStore } from '../store/authStore';
import axios from 'axios';
import { format } from 'date-fns';

const SecurityStatusCard = () => {
  const { t } = useTranslation();
  const { token } = useAuthStore();
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [securityStatus, setSecurityStatus] = useState(null);
  const [expanded, setExpanded] = useState(false);

  useEffect(() => {
    fetchSecurityStatus();
  }, []);

  const fetchSecurityStatus = async () => {
    setLoading(true);
    setError('');
    try {
      const response = await axios.get('/api/auth/security-status', {
        headers: { Authorization: `Bearer ${token}` }
      });
      setSecurityStatus(response.data);
    } catch (err) {
      setError(err.response?.data?.error || 'Failed to load security status');
    } finally {
      setLoading(false);
    }
  };

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

  if (error) {
    return (
      <Card>
        <CardContent>
          <Alert severity="error">{error}</Alert>
        </CardContent>
      </Card>
    );
  }

  const getPasswordExpiryStatus = () => {
    if (!securityStatus?.passwordExpiry) return null;
    const { expired, warning, daysRemaining } = securityStatus.passwordExpiry;
    
    if (expired) {
      return { severity: 'error', icon: <ErrorIcon />, message: t('security.passwordExpired') };
    }
    if (warning) {
      return {
        severity: 'warning',
        icon: <Warning />,
        message: t('security.passwordExpiresIn', { days: daysRemaining })
      };
    }
    return { severity: 'success', icon: <CheckCircle />, message: 'Password is valid' };
  };

  const passwordExpiryStatus = getPasswordExpiryStatus();

  return (
    <Card>
      <CardContent>
        <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'between', mb: 2 }}>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
            <Security color="primary" />
            <Typography variant="h6">{t('security.securityStatus')}</Typography>
          </Box>
          <IconButton
            size="small"
            onClick={() => setExpanded(!expanded)}
            sx={{
              transform: expanded ? 'rotate(180deg)' : 'rotate(0deg)',
              transition: 'transform 0.3s'
            }}
          >
            <ExpandMore />
          </IconButton>
        </Box>

        {/* Password Expiry Warning */}
        {passwordExpiryStatus && passwordExpiryStatus.severity !== 'success' && (
          <Alert
            severity={passwordExpiryStatus.severity}
            icon={passwordExpiryStatus.icon}
            sx={{ mb: 2 }}
          >
            {passwordExpiryStatus.message}
          </Alert>
        )}

        {/* Security Overview */}
        <List dense>
          <ListItem>
            <ListItemIcon>
              <Shield color={securityStatus?.twoFactorEnabled ? 'success' : 'disabled'} />
            </ListItemIcon>
            <ListItemText
              primary={t('security.twoFactorEnabled')}
              secondary={securityStatus?.twoFactorEnabled ? t('security.success') : 'Not enabled'}
            />
            <Chip
              size="small"
              label={securityStatus?.twoFactorEnabled ? 'ON' : 'OFF'}
              color={securityStatus?.twoFactorEnabled ? 'success' : 'default'}
            />
          </ListItem>

          <ListItem>
            <ListItemIcon>
              <Key color="primary" />
            </ListItemIcon>
            <ListItemText
              primary={t('security.passwordAge', { days: securityStatus?.passwordAge || 0 })}
              secondary={
                securityStatus?.passwordExpiry?.daysRemaining
                  ? t('security.passwordExpiresIn', { days: securityStatus.passwordExpiry.daysRemaining })
                  : null
              }
            />
          </ListItem>

          <ListItem>
            <ListItemIcon>
              <Devices color="primary" />
            </ListItemIcon>
            <ListItemText
              primary={t('security.activeSessions')}
              secondary={
                securityStatus?.lastActivity 
                  ? (() => {
                      try {
                        return format(new Date(securityStatus.lastActivity), 'PPpp');
                      } catch {
                        return null;
                      }
                    })()
                  : null
              }
            />
            <Chip size="small" label={securityStatus?.activeSessions || 0} color="primary" />
          </ListItem>

          <ListItem>
            <ListItemIcon>
              <Warning color={securityStatus?.failedLoginAttempts > 0 ? 'error' : 'success'} />
            </ListItemIcon>
            <ListItemText
              primary={t('security.failedAttempts')}
              secondary={
                securityStatus?.lastLogin?.timestamp 
                  ? (() => {
                      try {
                        return format(new Date(securityStatus.lastLogin.timestamp), 'PPpp');
                      } catch {
                        return 'Never';
                      }
                    })()
                  : 'Never'
              }
            />
            <Chip
              size="small"
              label={securityStatus?.failedLoginAttempts || 0}
              color={securityStatus?.failedLoginAttempts > 0 ? 'error' : 'success'}
            />
          </ListItem>
        </List>

        <Collapse in={expanded}>
          <Divider sx={{ my: 2 }} />
          <Typography variant="subtitle2" gutterBottom sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
            <History fontSize="small" />
            {t('security.recentActivity')}
          </Typography>
          {Array.isArray(securityStatus?.recentEvents) && securityStatus.recentEvents.length > 0 ? (
            <List dense>
              {securityStatus.recentEvents.slice(0, 5).map((event, index) => (
                <ListItem key={index} sx={{ pl: 0 }}>
                  <ListItemIcon>
                    {event.status === 'success' ? (
                      <CheckCircle fontSize="small" color="success" />
                    ) : event.status === 'failed' ? (
                      <ErrorIcon fontSize="small" color="error" />
                    ) : (
                      <Warning fontSize="small" color="warning" />
                    )}
                  </ListItemIcon>
                  <ListItemText
                    primary={event.type.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase())}
                    secondary={
                      event.timestamp 
                        ? (() => {
                            try {
                              return format(new Date(event.timestamp), 'PPpp');
                            } catch {
                              return 'Invalid date';
                            }
                          })()
                        : 'No timestamp'
                    }
                    primaryTypographyProps={{ variant: 'caption' }}
                    secondaryTypographyProps={{ variant: 'caption' }}
                  />
                  <Chip size="small" label={event.status} variant="outlined" />
                </ListItem>
              ))}
            </List>
          ) : (
            <Typography variant="caption" color="text.secondary" sx={{ display: 'block', p: 2, textAlign: 'center' }}>
              {t('security.noRecentActivity')}
            </Typography>
          )}
        </Collapse>
      </CardContent>
    </Card>
  );
};

export default SecurityStatusCard;
