import React, { useState, useCallback } from 'react';
import { useDispatch } from 'react-redux';
import { TextField, Button, Box, Typography, CircularProgress } from '@mui/material';
import { useLoginMutation } from '../../store/api/authApi';
import { setCredentials } from '../../store/slices/authSlice';

interface LoginFormData {
  email: string;
  password: string;
}

const LoginForm: React.FC = () => {
  const dispatch = useDispatch();
  const [login, { isLoading, error }] = useLoginMutation();
  const [formData, setFormData] = useState<LoginFormData>({
    email: '',
    password: ''
  });

  const handleChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
  }, []);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      const result = await login(formData).unwrap();
      dispatch(setCredentials(result));
    } catch (err) {
      console.error('Failed to login:', err);
    }
  };

  return (
    <Box component="form" onSubmit={handleSubmit} sx={{ maxWidth: 400, mx: 'auto', mt: 4 }}>
      <Typography variant="h5" component="h1" gutterBottom>
        Login to myCRM
      </Typography>
      
      <TextField
        fullWidth
        margin="normal"
        label="Email"
        type="email"
        name="email"
        value={formData.email}
        onChange={handleChange}
        required
        aria-label="Email input"
        error={!!error}
      />
      
      <TextField
        fullWidth
        margin="normal"
        label="Password"
        type="password"
        name="password"
        value={formData.password}
        onChange={handleChange}
        required
        aria-label="Password input"
        error={!!error}
      />
      
      {error && (
        <Typography color="error" sx={{ mt: 2 }}>
          {error instanceof Error ? error.message : 'Login failed'}
        </Typography>
      )}
      
      <Button
        type="submit"
        variant="contained"
        fullWidth
        sx={{ mt: 3 }}
        disabled={isLoading}
        aria-label="Login button"
      >
        {isLoading ? <CircularProgress size={24} /> : 'Login'}
      </Button>
    </Box>
  );
};

export default LoginForm;