import { useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { Alert, Button, Center, Paper, PasswordInput, Stack, Text, TextInput, Title } from '@mantine/core';
import { login } from '../store/authSlice';

export default function LoginForm() {
  const dispatch = useDispatch();
  const { loading, error } = useSelector((state) => state.auth);
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');

  function handleSubmit(event) {
    event.preventDefault();
    dispatch(login({ username, password }));
  }

  return (
    <Center mih="100vh" p="md">
      <Paper shadow="md" radius="lg" p="xl" w={380} maw="100%">
        <form onSubmit={handleSubmit}>
          <Stack gap="md">
            <div>
              <Title order={2}>Listing - Suggest Price</Title>
              <Text c="dimmed" size="sm">
                Đăng nhập bằng tài khoản ERP
              </Text>
            </div>

            {error && (
              <Alert color="red" variant="light">
                {error}
              </Alert>
            )}

            <TextInput
              label="Email"
              value={username}
              onChange={(e) => setUsername(e.target.value)}
              placeholder="you@company.com"
              required
            />
            <PasswordInput
              label="Mật khẩu"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              required
            />
            <Button type="submit" fullWidth loading={loading} disabled={!username.trim()}>
              Đăng nhập
            </Button>
          </Stack>
        </form>
      </Paper>
    </Center>
  );
}
