import React, { useState } from 'react';
import { useDispatch } from 'react-redux';
import { loginSuccess, setError } from '../features/auth/authSlice';
import { Box, Button, TextField, Typography, Alert } from '@mui/material';

const LoginPage = () => {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setErrorState] = useState(null);
  const dispatch = useDispatch();

  const handleLogin = () => {
    if (!email || !password) {
      setErrorState('Email and Password are required.');
      return;
    }

    // Simulate login API call
    try {
      dispatch(loginSuccess({ email })); // Replace with actual API response
    } catch (err) {
      dispatch(setError(err.message));
      setErrorState('Invalid credentials.');
    }
  };

  return (
    <Box p={3} maxWidth="400px" mx="auto">
      <Typography variant="h5" mb={2}>Login</Typography>
      {error && <Alert severity="error">{error}</Alert>}
      <TextField
        label="Email"
        fullWidth
        margin="normal"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
      />
      <TextField
        label="Password"
        type="password"
        fullWidth
        margin="normal"
        value={password}
        onChange={(e) => setPassword(e.target.value)}
      />
      <Button variant="contained" color="primary" fullWidth onClick={handleLogin}>
        Login
      </Button>
    </Box>
  );
};

export default LoginPage;