import React, { useState, useEffect } from 'react';
import { Modal, Box, Typography, TextField, Button, CircularProgress, Alert, FormControlLabel, Checkbox } from '@mui/material';
import type { SetPasswordRequestDto } from '../../../models/dtos/Usuarios/SetPasswordRequestDto';
import type { UsuarioDto } from '../../../models/dtos/Usuarios/UsuarioDto';

const modalStyle = { /* ... (mismo estilo) ... */
    position: 'absolute' as 'absolute',
    top: '50%',
    left: '50%',
    transform: 'translate(-50%, -50%)',
    width: 400,
    bgcolor: 'background.paper',
    border: '2px solid #000',
    boxShadow: 24,
    p: 4,
};

interface SetPasswordModalProps {
  open: boolean;
  onClose: () => void;
  onSubmit: (userId: number, data: SetPasswordRequestDto) => Promise<void>;
  usuario: UsuarioDto | null; // Usuario para el cual se setea la clave
  errorMessage?: string | null;
  clearErrorMessage: () => void;
}

const SetPasswordModal: React.FC<SetPasswordModalProps> = ({
  open,
  onClose,
  onSubmit,
  usuario,
  errorMessage,
  clearErrorMessage
}) => {
  const [newPassword, setNewPassword] = useState('');
  const [confirmNewPassword, setConfirmNewPassword] = useState('');
  const [forceChange, setForceChange] = useState(true);
  const [loading, setLoading] = useState(false);
  const [localErrors, setLocalErrors] = useState<{ [key: string]: string | null }>({});

  useEffect(() => {
    if (open) {
        setNewPassword('');
        setConfirmNewPassword('');
        setForceChange(true);
        setLocalErrors({});
        clearErrorMessage();
    }
  }, [open, clearErrorMessage]);

  const validate = (): boolean => {
    const errors: { [key: string]: string | null } = {};
    if (!newPassword) errors.newPassword = 'La nueva contraseña es obligatoria.';
    else if (newPassword.length < 6) errors.newPassword = 'La contraseña debe tener al menos 6 caracteres.';
    if (newPassword !== confirmNewPassword) errors.confirmNewPassword = 'Las contraseñas no coinciden.';
    if (usuario && usuario.user.toLowerCase() === newPassword.toLowerCase()) errors.newPassword = 'La contraseña no puede ser igual al nombre de usuario.'

    setLocalErrors(errors);
    return Object.keys(errors).length === 0;
  };

  const handleInputChange = (fieldName: string) => {
    if (localErrors[fieldName]) {
        setLocalErrors(prev => ({ ...prev, [fieldName]: null }));
    }
    if (errorMessage) clearErrorMessage();
  };


  const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    clearErrorMessage();
    if (!validate() || !usuario) return;

    setLoading(true);
    try {
      const dataToSubmit: SetPasswordRequestDto = { newPassword, forceChangeOnNextLogin: forceChange };
      await onSubmit(usuario.id, dataToSubmit);
      onClose();
    } catch (error) {
      console.error("Error en submit de SetPasswordModal:", error);
    } finally {
       setLoading(false);
    }
  };

  return (
    <Modal open={open} onClose={onClose}>
      <Box sx={modalStyle}>
        <Typography variant="h6" component="h2" gutterBottom>
          Establecer Contraseña para {usuario?.user || ''}
        </Typography>
        <Box component="form" onSubmit={handleSubmit} sx={{ mt: 1 }}>
          <TextField label="Nueva Contraseña" type="password" fullWidth required value={newPassword}
            onChange={(e)=>{setNewPassword(e.target.value); handleInputChange('newPassword');}} margin="dense"
            error={!!localErrors.newPassword} helperText={localErrors.newPassword || ''}
            disabled={loading} autoFocus
          />
          <TextField label="Confirmar Nueva Contraseña" type="password" fullWidth required value={confirmNewPassword}
            onChange={(e)=>{setConfirmNewPassword(e.target.value); handleInputChange('confirmNewPassword');}} margin="dense"
            error={!!localErrors.confirmNewPassword} helperText={localErrors.confirmNewPassword || ''}
            disabled={loading}
          />
          <FormControlLabel
            control={<Checkbox checked={forceChange} onChange={(e) => setForceChange(e.target.checked)} disabled={loading}/>}
            label="Forzar cambio en próximo inicio de sesión"
            sx={{ mt: 1 }}
          />
          {errorMessage && <Alert severity="error" sx={{ mt: 2, width: '100%' }}>{errorMessage}</Alert>}
          <Box sx={{ mt: 3, display: 'flex', justifyContent: 'flex-end', gap: 1 }}>
            <Button onClick={onClose} color="secondary" disabled={loading}>Cancelar</Button>
            <Button type="submit" variant="contained" disabled={loading}>
              {loading ? <CircularProgress size={24} /> : 'Establecer Contraseña'}
            </Button>
          </Box>
        </Box>
      </Box>
    </Modal>
  );
};

export default SetPasswordModal;