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

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

  const handleRegister = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setLoading(true);
    try {
      await signUp.email({
        email,
        password,
        name: email.split('@')[0], // Default name
      }, {
        onSuccess: () => {
          navigate('/');
        },
        onError: (ctx) => {
          toast.danger(ctx.error.message);
        }
      });
    } catch (err) {
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="flex flex-col items-center justify-center min-h-[calc(100vh-64px)] p-4">
      <Card className="w-full max-w-md">
        <Card.Header>
          <Card.Title className="text-2xl font-bold text-center w-full">注册 HLAE 中文站</Card.Title>
        </Card.Header>
        <Form validationBehavior="native" onSubmit={handleRegister}>
          <Card.Content className="flex flex-col gap-6">
            <TextField
              isRequired
              name="email"
              type="email"
              value={email}
              onChange={setEmail}
            >
              <Label>邮箱</Label>
              <Input placeholder="请输入您的邮箱" variant="secondary" />
              <FieldError />
            </TextField>

            <TextField
              isRequired
              name="password"
              type="password"
              value={password}
              onChange={setPassword}
            >
              <Label>密码</Label>
              <Input placeholder="请输入您的密码" variant="secondary" />
              <FieldError />
            </TextField>
          </Card.Content>
          <Card.Footer className="flex flex-col gap-3 mt-2">
            <Button type="submit" isPending={loading} fullWidth className="font-bold">
              注册
            </Button>
            <Button as={Link} to="/login" variant="tertiary" fullWidth className="font-bold">
              已有账号？登录
            </Button>
            <div className="flex justify-center mt-2">
              <Link to="/" className="text-sm text-default-500 hover:text-primary transition-colors flex items-center gap-1">
                <span>← 返回首页</span>
              </Link>
            </div>
          </Card.Footer>
        </Form>
      </Card>
    </div>
  );
}
