import {useState} from 'react';
import {useNavigate} from 'react-router-dom';

import './Login.css';

import axios from 'axios';


export default function Login() {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const navigate = useNavigate();
  const handleSubmit = async e => {
    e.preventDefault();
    try {
      const resp = await axios.post(
        'https://api.rop.cc/auth',
        {username, password},
        {withCredentials: true}
      );
      console.log('接收到resp：', resp);
      // 假设后端返回 { token: 'xxxx' } 保留本地token
      // localStorage.setItem('jwt', resp.data.token);
      // localStorage.setItem('_uname', resp.data.username);
      // 跳转到首页或登录前尝试访问的页面
      navigate('/', {replace: true});
    } catch (err) {
      console.log(err)
      alert(`[[Login failed]] error = ${err}`);
    }
  };
  return (<form className="login" onSubmit={handleSubmit}>
    <h2>Login</h2>
    <input
      value={username}
      onChange={e => setUsername(e.target.value)}
      placeholder="username"
    />
    <input
      type="password"
      value={password}
      onChange={e => setPassword(e.target.value)}
      placeholder="password"
    />
    <button type="submit">submit</button>
  </form>);
}
