import React, { useState } from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
  Button,
  Box,
  IconButton,
  InputAdornment,
  Typography,
  Alert
} from '@mui/material';
import { Visibility, VisibilityOff, Close } from '@mui/icons-material';
import { useTranslation } from 'react-i18next';
import { useSnackbar } from '@/hooks/useSnackbar';
import logger from '@/utils/logger';

interface ChangePasswordDialogProps {
  open: boolean;
  onClose: () => void;
  changeUserPassword: (data: { password: string; new_password: string }) => Promise<void>;
}

interface PasswordFormData {
  currentPassword: string;
  newPassword: string;
  confirmPassword: string;
}

/**
 * 修改密码对话框
 */
function ChangePasswordDialog({ open, onClose, changeUserPassword }: ChangePasswordDialogProps) {
  const { t } = useTranslation();
  const { showMessage } = useSnackbar();
  
  const [formData, setFormData] = useState<PasswordFormData>({
    currentPassword: '',
    newPassword: '',
    confirmPassword: ''
  });
  
  const [showPasswords, setShowPasswords] = useState({
    current: false,
    new: false,
    confirm: false
  });
  
  const [loading, setLoading] = useState(false);
  const [errors, setErrors] = useState<Partial<PasswordFormData>>({});

  // 重置表单
  const resetForm = () => {
    setFormData({
      currentPassword: '',
      newPassword: '',
      confirmPassword: ''
    });
    setErrors({});
    setShowPasswords({
      current: false,
      new: false,
      confirm: false
    });
  };

  // 处理关闭
  const handleClose = () => {
    resetForm();
    onClose();
  };

  // 处理输入变化
  const handleInputChange = (field: keyof PasswordFormData) => (event: React.ChangeEvent<HTMLInputElement>) => {
    const value = event.target.value;
    setFormData(prev => ({
      ...prev,
      [field]: value
    }));
    
    // 清除对应字段的错误
    if (errors[field]) {
      setErrors(prev => ({
        ...prev,
        [field]: undefined
      }));
    }
  };

  // 切换密码可见性
  const togglePasswordVisibility = (field: 'current' | 'new' | 'confirm') => {
    setShowPasswords(prev => ({
      ...prev,
      [field]: !prev[field]
    }));
  };

  // 验证表单
  const validateForm = (): boolean => {
    const newErrors: Partial<PasswordFormData> = {};
    
    if (!formData.currentPassword.trim()) {
      newErrors.currentPassword = t('setting.currentPasswordRequired');
    }
    
    if (!formData.newPassword.trim()) {
      newErrors.newPassword = t('setting.newPasswordRequired');
    } else if (formData.newPassword.length < 6) {
      newErrors.newPassword = t('setting.passwordMinLength');
    }
    
    if (!formData.confirmPassword.trim()) {
      newErrors.confirmPassword = t('setting.confirmPasswordRequired');
    } else if (formData.newPassword !== formData.confirmPassword) {
      newErrors.confirmPassword = t('setting.passwordMismatch');
    }
    
    if (formData.currentPassword === formData.newPassword) {
      newErrors.newPassword = t('setting.newPasswordSameAsCurrent');
    }
    
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  // 提交修改
  const handleSubmit = async () => {
    if (!validateForm()) {
      return;
    }
    
    setLoading(true);
    try {
      await changeUserPassword({
        password: formData.currentPassword,
        new_password: formData.newPassword
      });
      
      showMessage.success(t('setting.passwordChangeSuccess'));
      handleClose();
    } catch (error: any) {
      logger.error('修改密码失败:', error);
      if (error.response?.status === 400) {
        showMessage.error(t('setting.currentPasswordIncorrect'));
      } else {
        showMessage.error(t('setting.passwordChangeError'));
      }
    } finally {
      setLoading(false);
    }
  };

  return (
    <Dialog
      open={open}
      onClose={handleClose}
      maxWidth="sm"
      fullWidth
      PaperProps={{
        sx: { borderRadius: 2 }
      }}
    >
      <DialogTitle sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <Typography variant="h6" component="div">
          {t('setting.changePassword')}
        </Typography>
        <IconButton
          onClick={handleClose}
          size="small"
          sx={{ color: 'text.secondary' }}
        >
          <Close />
        </IconButton>
      </DialogTitle>
      
      <DialogContent dividers>
        <Box sx={{ display: 'flex', flexDirection: 'column', gap: 3, pt: 1 }}>
          <Alert severity="info" sx={{ mb: 1 }}>
            {t('setting.passwordSecurityTip')}
          </Alert>
          
          <Typography variant="body2" color="text.secondary" sx={{ mb: 3 }}>
            {t('setting.passwordUpdateTip')}
          </Typography>
          
          {/* 当前密码 */}
          <TextField
            fullWidth
            label={t('setting.currentPassword')}
            type={showPasswords.current ? 'text' : 'password'}
            value={formData.currentPassword}
            onChange={handleInputChange('currentPassword')}
            error={!!errors.currentPassword}
            helperText={errors.currentPassword}
            InputProps={{
              endAdornment: (
                <InputAdornment position="end">
                  <IconButton
                    onClick={() => togglePasswordVisibility('current')}
                    edge="end"
                    size="small"
                  >
                    {showPasswords.current ? <VisibilityOff /> : <Visibility />}
                  </IconButton>
                </InputAdornment>
              )
            }}
          />
          
          {/* 新密码 */}
          <TextField
            fullWidth
            label={t('setting.newPassword')}
            type={showPasswords.new ? 'text' : 'password'}
            value={formData.newPassword}
            onChange={handleInputChange('newPassword')}
            error={!!errors.newPassword}
            helperText={errors.newPassword || '密码长度至少6位'}
            InputProps={{
              endAdornment: (
                <InputAdornment position="end">
                  <IconButton
                    onClick={() => togglePasswordVisibility('new')}
                    edge="end"
                    size="small"
                  >
                    {showPasswords.new ? <VisibilityOff /> : <Visibility />}
                  </IconButton>
                </InputAdornment>
              )
            }}
          />
          
          {/* 确认新密码 */}
          <TextField
            fullWidth
            label={t('setting.confirmNewPassword')}
            type={showPasswords.confirm ? 'text' : 'password'}
            value={formData.confirmPassword}
            onChange={handleInputChange('confirmPassword')}
            error={!!errors.confirmPassword}
            helperText={errors.confirmPassword}
            InputProps={{
              endAdornment: (
                <InputAdornment position="end">
                  <IconButton
                    onClick={() => togglePasswordVisibility('confirm')}
                    edge="end"
                    size="small"
                  >
                    {showPasswords.confirm ? <VisibilityOff /> : <Visibility />}
                  </IconButton>
                </InputAdornment>
              )
            }}
          />
        </Box>
      </DialogContent>
      
      <DialogActions sx={{ p: 3, gap: 1 }}>
        <Button
          onClick={handleClose}
          variant="outlined"
          disabled={loading}
        >
          {t('setting.cancel')}
        </Button>
        <Button
          onClick={handleSubmit}
          variant="contained"
          disabled={loading}
          sx={{ minWidth: 100 }}
        >
          {loading ? t('setting.changing') : t('setting.confirmChange')}
        </Button>
      </DialogActions>
    </Dialog>
  );
}

export default ChangePasswordDialog;