import React, { useState, useEffect } from 'react';
import { 
  TextField, 
  Button, 
  Dialog, 
  DialogActions, 
  DialogContent, 
  DialogTitle,
  CircularProgress
} from '@mui/material';

const UpdateModal = ({ user, onUpdate, onClose, open }) => {
  const [updatedUser, setUpdatedUser] = useState({});
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  // Initialize form with user data when modal opens or user changes
  useEffect(() => {
    if (user) {
      setUpdatedUser({ ...user });
    }
  }, [user, open]);

  const handleChange = (field, value) => {
    setUpdatedUser(prev => ({
      ...prev,
      [field]: value
    }));
  };

  const handleSave = async () => {
    if (!updatedUser.userId) {
      setError('User ID is required');
      return;
    }

    setLoading(true);
    setError(null);

    try {
      await onUpdate(updatedUser);
      onClose();
    } catch (err) {
      console.error('Update failed:', err);
      setError(err.message || 'Failed to update user');
    } finally {
      setLoading(false);
    }
  };

  if (!user) {
    return null; // Or render a loading state/message
  }

  return (
    <Dialog open={open} onClose={onClose} maxWidth="sm" fullWidth>
      <DialogTitle>Update User</DialogTitle>
      <DialogContent>
        {error && (
          <div style={{ color: 'red', marginBottom: '16px' }}>
            {error}
          </div>
        )}

        <TextField
          margin="dense"
          label="User ID"
          fullWidth
          variant="outlined"
          value={updatedUser.userId || ''}
          onChange={(e) => handleChange('userId', e.target.value)}
          disabled // Typically IDs shouldn't be editable
        />

        <TextField
          margin="dense"
          label="Username"
          fullWidth
          variant="outlined"
          value={updatedUser.username || ''}
          onChange={(e) => handleChange('username', e.target.value)}
          required
        />

        <TextField
          margin="dense"
          label="Full Name"
          fullWidth
          variant="outlined"
          value={updatedUser.fullName || ''}
          onChange={(e) => handleChange('fullName', e.target.value)}
        />

        <TextField
          margin="dense"
          label="Email"
          fullWidth
          variant="outlined"
          type="email"
          value={updatedUser.email || ''}
          onChange={(e) => handleChange('email', e.target.value)}
        />

        <TextField
          margin="dense"
          label="Mobile Number"
          fullWidth
          variant="outlined"
          value={updatedUser.mobno || ''}
          onChange={(e) => handleChange('mobno', e.target.value)}
        />

        <TextField
          margin="dense"
          label="User Group"
          fullWidth
          variant="outlined"
          value={updatedUser.usergrpname || ''}
          onChange={(e) => handleChange('usergrpname', e.target.value)}
        />
      </DialogContent>
      <DialogActions>
        <Button onClick={onClose} color="secondary">
          Cancel
        </Button>
        <Button 
          onClick={handleSave} 
          color="primary"
          variant="contained"
          disabled={loading}
        >
          {loading ? <CircularProgress size={24} /> : 'Save'}
        </Button>
      </DialogActions>
    </Dialog>
  );
};

export default UpdateModal;