import React, { useState, useCallback, memo } from 'react';
import { useDispatch } from 'react-redux';
import { TextField, Button, Paper, Typography, Box, CircularProgress } from '@mui/material';
import { login } from '../../store/slices/authSlice';
import { ILoginFormData } from '../../types/interfaces';
import { validateEmail } from '../../utils/validation';

const LoginForm: React.FC = memo(() => {
  const dispatch = useDispatch();
  const [formData, setFormData] = useState<ILoginFormData>({
    email: '',
    password: ''
  });
  const [errors, setErrors] = useState<Partial<ILoginFormData>>({
    email: '',
    password: ''
  });
  const [isLoading, setIsLoading] = useState(false);

  const validateForm = useCallback((): boolean => {
    const newErrors: Partial<ILoginFormData> = {};
    if (!validateEmail(formData.email)) {
      newErrors.email = 'Please enter a valid email address';
    }
    if (formData.password.length < 8) {
      newErrors.password = 'Password must be at least 8 characters';
    }
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  }, [formData]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!validateForm()) return;

    try {
      setIsLoading(true);
      await dispatch(login(formData));
    } catch (err) {
      setErrors({
        ...errors,
        password: 'Invalid credentials. Please try again.'
      });
    } finally {
      setIsLoading(false);
    }
  };

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

  return (
    <Paper elevation={3} sx={{ p: 4, maxWidth: 400, mx: 'auto' }}>
      <Typography variant="h5" component="h1" gutterBottom>
        Caregiver Login
      </Typography>
      <form onSubmit={handleSubmit} noValidate>
        <Box sx={{ mb: 2 }}>
          <TextField
            fullWidth
            label="Email"
            type="email"
            name="email"
            value={formData.email}
            onChange={handleInputChange}
            error={!!errors.email}
            helperText={errors.email}
            required
            aria-label="Email input"
            inputProps={{
              'aria-describedby': 'email-error'
            }}
          />
        </Box>
        <Box sx={{ mb: 2 }}>
          <TextField
            fullWidth
            label="Password"
            type="password"
            name="password"
            value={formData.password}
            onChange={handleInputChange}
            error={!!errors.password}
            helperText={errors.password}
            required
            aria-label="Password input"
            inputProps={{
              'aria-describedby': 'password-error'
            }}
          />
        </Box>
        <Button
          type="submit"
          variant="contained"
          color="primary"
          fullWidth
          disabled={isLoading}
          aria-label="Login button"
        >
          {isLoading ? <CircularProgress size={24} /> : 'Login'}
        </Button>
      </form>
    </Paper>
  );
});

LoginForm.displayName = 'LoginForm';

export default LoginForm;