import { useState } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import { Card, Input, Button, Form, toast } from '@heroui/react';
import { signIn } from '../../lib/auth-client';

export default function LoginPage() {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    try {
      await signIn.email({
        email,
        password,
      }, {
        onSuccess: () => {
          navigate('/');
        },
        onError: (ctx) => {
          toast.danger(ctx.error.message);
        }
      });
    } catch (err) {
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="flex items-center justify-center min-h-screen p-4">
      <Card className="w-full max-w-md p-6">
        <h1 className="text-2xl font-bold mb-6 text-center">登录 HLAE 中文站</h1>
        <Form validationBehavior="native" onSubmit={handleLogin} className="flex flex-col gap-4">
          <Input
            isRequired
            label="邮箱"
            placeholder="请输入您的邮箱"
            type="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
          />
          <Input
            isRequired
            label="密码"
            placeholder="请输入您的密码"
            type="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
          />
          <Button color="primary" type="submit" isLoading={loading}>
            登录
          </Button>
          <div className="text-center text-sm">
            还没有账号？ <Link to="/register" className="text-primary hover:underline">去注册</Link>
          </div>
        </Form>
      </Card>
    </div>
  );
}
