import React, { useEffect, useState } from 'react';
import {
  Box,
  LinearProgress,
  Typography,
  List,
  ListItem,
  ListItemIcon,
  ListItemText,
  Collapse
} from '@mui/material';
import { CheckCircle, Cancel, Info } from '@mui/icons-material';
import { useTranslation } from 'react-i18next';

const PasswordStrengthMeter = ({ password, username = '', email = '' }) => {
  const { t } = useTranslation();
  const [strength, setStrength] = useState({ score: 0, level: 'veryWeak', feedback: [] });
  const [requirements, setRequirements] = useState({
    minLength: false,
    uppercase: false,
    lowercase: false,
    number: false,
    special: false,
    noUsername: true,
    noEmail: true
  });

  useEffect(() => {
    if (!password) {
      setStrength({ score: 0, level: 'veryWeak', feedback: [] });
      setRequirements({
        minLength: false,
        uppercase: false,
        lowercase: false,
        number: false,
        special: false,
        noUsername: true,
        noEmail: true
      });
      return;
    }

    // Check requirements
    const reqs = {
      minLength: password.length >= 12,
      uppercase: /[A-Z]/.test(password),
      lowercase: /[a-z]/.test(password),
      number: /[0-9]/.test(password),
      special: /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(password),
      noUsername: username ? !password.toLowerCase().includes(username.toLowerCase()) : true,
      noEmail: email ? !password.toLowerCase().includes(email.split('@')[0].toLowerCase()) : true
    };
    setRequirements(reqs);

    // Calculate score
    let score = 0;
    if (reqs.minLength) score += 20;
    if (reqs.uppercase) score += 15;
    if (reqs.lowercase) score += 15;
    if (reqs.number) score += 15;
    if (reqs.special) score += 15;
    if (password.length > 15) score += 10;
    if (password.length > 20) score += 10;
    if (!reqs.noUsername || !reqs.noEmail) score -= 30;

    // Determine level
    let level = 'veryWeak';
    let color = '#d32f2f';
    if (score >= 91) {
      level = 'veryStrong';
      color = '#2e7d32';
    } else if (score >= 76) {
      level = 'strong';
      color = '#66bb6a';
    } else if (score >= 51) {
      level = 'good';
      color = '#fbc02d';
    } else if (score >= 26) {
      level = 'weak';
      color = '#f57c00';
    }

    setStrength({
      score: Math.max(0, Math.min(100, score)),
      level,
      color,
      feedback: []
    });
  }, [password, username, email]);

  const getStrengthColor = () => {
    if (strength.score >= 91) return '#2e7d32'; // green
    if (strength.score >= 76) return '#66bb6a'; // light green
    if (strength.score >= 51) return '#fbc02d'; // yellow
    if (strength.score >= 26) return '#f57c00'; // orange
    return '#d32f2f'; // red
  };

  const getStrengthLabel = () => {
    if (strength.score >= 91) return t('security.veryStrong');
    if (strength.score >= 76) return t('security.strong');
    if (strength.score >= 51) return t('security.good');
    if (strength.score >= 26) return t('security.weak');
    return t('security.veryWeak');
  };

  if (!password) return null;

  return (
    <Box sx={{ mt: 2 }}>
      <Box sx={{ display: 'flex', alignItems: 'center', gap: 2, mb: 1 }}>
        <Box sx={{ flex: 1 }}>
          <Typography variant="caption" color="text.secondary" sx={{ mb: 0.5, display: 'block' }}>
            {t('security.passwordStrength')}
          </Typography>
          <LinearProgress
            variant="determinate"
            value={strength.score}
            sx={{
              height: 8,
              borderRadius: 1,
              backgroundColor: 'rgba(0,0,0,0.1)',
              '& .MuiLinearProgress-bar': {
                backgroundColor: getStrengthColor(),
                transition: 'all 0.3s ease'
              }
            }}
          />
        </Box>
        <Typography
          variant="body2"
          fontWeight="bold"
          sx={{ color: getStrengthColor(), minWidth: 80, textAlign: 'right' }}
        >
          {getStrengthLabel()}
        </Typography>
      </Box>

      <Collapse in={password.length > 0}>
        <Box sx={{ mt: 2, p: 1.5, bgcolor: 'action.hover', borderRadius: 1 }}>
          <Typography variant="caption" color="text.secondary" sx={{ display: 'flex', alignItems: 'center', gap: 0.5, mb: 1 }}>
            <Info fontSize="small" />
            {t('security.requirements')}
          </Typography>
          <List dense disablePadding>
            <ListItem disablePadding sx={{ py: 0.25 }}>
              <ListItemIcon sx={{ minWidth: 28 }}>
                {requirements.minLength ? (
                  <CheckCircle fontSize="small" sx={{ color: 'success.main' }} />
                ) : (
                  <Cancel fontSize="small" sx={{ color: 'error.main' }} />
                )}
              </ListItemIcon>
              <ListItemText
                primary={t('security.minLength')}
                primaryTypographyProps={{ variant: 'caption' }}
              />
            </ListItem>
            <ListItem disablePadding sx={{ py: 0.25 }}>
              <ListItemIcon sx={{ minWidth: 28 }}>
                {requirements.uppercase ? (
                  <CheckCircle fontSize="small" sx={{ color: 'success.main' }} />
                ) : (
                  <Cancel fontSize="small" sx={{ color: 'error.main' }} />
                )}
              </ListItemIcon>
              <ListItemText
                primary={t('security.uppercase')}
                primaryTypographyProps={{ variant: 'caption' }}
              />
            </ListItem>
            <ListItem disablePadding sx={{ py: 0.25 }}>
              <ListItemIcon sx={{ minWidth: 28 }}>
                {requirements.lowercase ? (
                  <CheckCircle fontSize="small" sx={{ color: 'success.main' }} />
                ) : (
                  <Cancel fontSize="small" sx={{ color: 'error.main' }} />
                )}
              </ListItemIcon>
              <ListItemText
                primary={t('security.lowercase')}
                primaryTypographyProps={{ variant: 'caption' }}
              />
            </ListItem>
            <ListItem disablePadding sx={{ py: 0.25 }}>
              <ListItemIcon sx={{ minWidth: 28 }}>
                {requirements.number ? (
                  <CheckCircle fontSize="small" sx={{ color: 'success.main' }} />
                ) : (
                  <Cancel fontSize="small" sx={{ color: 'error.main' }} />
                )}
              </ListItemIcon>
              <ListItemText
                primary={t('security.number')}
                primaryTypographyProps={{ variant: 'caption' }}
              />
            </ListItem>
            <ListItem disablePadding sx={{ py: 0.25 }}>
              <ListItemIcon sx={{ minWidth: 28 }}>
                {requirements.special ? (
                  <CheckCircle fontSize="small" sx={{ color: 'success.main' }} />
                ) : (
                  <Cancel fontSize="small" sx={{ color: 'error.main' }} />
                )}
              </ListItemIcon>
              <ListItemText
                primary={t('security.special')}
                primaryTypographyProps={{ variant: 'caption' }}
              />
            </ListItem>
            {username && (
              <ListItem disablePadding sx={{ py: 0.25 }}>
                <ListItemIcon sx={{ minWidth: 28 }}>
                  {requirements.noUsername ? (
                    <CheckCircle fontSize="small" sx={{ color: 'success.main' }} />
                  ) : (
                    <Cancel fontSize="small" sx={{ color: 'error.main' }} />
                  )}
                </ListItemIcon>
                <ListItemText
                  primary={t('security.noUsername')}
                  primaryTypographyProps={{ variant: 'caption' }}
                />
              </ListItem>
            )}
          </List>
        </Box>
      </Collapse>
    </Box>
  );
};

export default PasswordStrengthMeter;
