import React, { useState } from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
  Button,
  Alert,
  CircularProgress,
  Typography,
  Box
} from '@mui/material';
import { useTranslation } from 'react-i18next';
import { useAuthStore } from '../store/authStore';
import PasswordStrengthMeter from './PasswordStrengthMeter';
import { useErrorNotification } from './ErrorNotificationProvider';

const ChangePasswordDialog = ({ open, onClose, onSuccess }) => {
  const { t } = useTranslation();
  const { token, clearPasswordFlag } = useAuthStore();
  const { showError, showSuccess } = useErrorNotification();
  const [currentPassword, setCurrentPassword] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError('');

    if (newPassword.length < 8) {
      setError(t('auth.passwordTooShort'));
      return;
    }

    if (newPassword !== confirmPassword) {
      setError(t('auth.passwordsDoNotMatch'));
      return;
    }

    setLoading(true);

    try {
      const response = await fetch('/api/auth/change-password', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${token}`
        },
        body: JSON.stringify({
          currentPassword,
          newPassword
        })
      });

      if (response.ok) {
        clearPasswordFlag();
        
        // Show success notification
        showSuccess(t('auth.passwordChangeSuccess') || 'Password changed successfully!', {
          duration: 4000
        });
        
        if (onSuccess) onSuccess();
        if (onClose) onClose();
        setCurrentPassword('');
        setNewPassword('');
        setConfirmPassword('');
        setError('');
      } else {
        const data = await response.json();
        // Handle detailed password policy errors
        if (data.details) {
          setError(data.details.join('. '));
          // Also show as notification for better visibility
          showError(
            new Error(data.details.join('. ')),
            {
              title: t('errors.validation.title'),
              duration: 10000
            }
          );
        } else {
          setError(data.error || t('auth.passwordChangeFailed'));
          showError(
            new Error(data.error || t('auth.passwordChangeFailed')),
            {
              title: t('auth.changePasswordFailed') || 'Password Change Failed',
              duration: 6000
            }
          );
        }
      }
    } catch (err) {
      setError(t('auth.passwordChangeFailed'));
      showError(err, {
        title: t('auth.changePasswordFailed') || 'Password Change Failed',
        defaultMessage: t('auth.passwordChangeFailed'),
        duration: 6000
      });
    } finally {
      setLoading(false);
    }
  };

  return (
    <Dialog 
      open={open} 
      onClose={null}
      disableEscapeKeyDown
      maxWidth="sm" 
      fullWidth
    >
      <DialogTitle>{t('auth.changePasswordRequired')}</DialogTitle>
      <DialogContent>
        <Alert severity="warning" sx={{ mb: 2 }}>
          {t('auth.changePasswordWarning')}
        </Alert>
        
        {error && (
          <Alert severity="error" sx={{ mb: 2 }} onClose={() => setError('')}>
            {error}
          </Alert>
        )}

        <Box component="form" onSubmit={handleSubmit}>
          <TextField
            fullWidth
            type="password"
            label={t('auth.currentPassword')}
            value={currentPassword}
            onChange={(e) => setCurrentPassword(e.target.value)}
            required
            size="small"
            sx={{ mb: 2, mt: 1 }}
            autoFocus
          />
          
          <TextField
            fullWidth
            type="password"
            label={t('auth.newPassword')}
            value={newPassword}
            onChange={(e) => setNewPassword(e.target.value)}
            required
            size="small"
            sx={{ mb: 1 }}
          />

          <PasswordStrengthMeter password={newPassword} />
          
          <TextField
            fullWidth
            type="password"
            label={t('auth.confirmPassword')}
            value={confirmPassword}
            onChange={(e) => setConfirmPassword(e.target.value)}
            required
            size="small"
            sx={{ mt: 2 }}
          />
        </Box>
      </DialogContent>
      <DialogActions sx={{ px: 3, pb: 2 }}>
        <Button 
          onClick={handleSubmit}
          variant="contained"
          disabled={loading || !currentPassword || !newPassword || !confirmPassword}
          fullWidth
        >
          {loading ? <CircularProgress size={24} /> : t('auth.changePassword')}
        </Button>
      </DialogActions>
    </Dialog>
  );
};

export default ChangePasswordDialog;
