import { useState } from 'react';
import { useNavigate } from 'react-router';
import { Button, Card, Input, message, Typography } from 'antd';
import { login } from '@/services/auth';
import { apiErrorMessage } from '@/services/api';

const { Title, Text } = Typography;

export default function LoginPage() {
    const navigate = useNavigate();
    const [token, setToken] = useState('');
    const [loading, setLoading] = useState(false);

    const onSubmit = async () => {
        if (!token.trim()) return;
        setLoading(true);
        try {
            await login(token.trim());
            message.success('登录成功');
            navigate('/collection', { replace: true });
        } catch (e) {
            message.error(apiErrorMessage(e));
        } finally {
            setLoading(false);
        }
    };

    return (
        <div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', background: '#f5f5f5' }}>
            <Card style={{ width: 420 }}>
                <Title level={3} style={{ marginTop: 0 }}>Ozon 发布工作台</Title>
                <Text type="secondary">请输入访问 Token（对应服务端 .env 的 APP_TOKEN）</Text>
                <Input.Password
                    placeholder="APP_TOKEN"
                    value={token}
                    onChange={(e) => setToken(e.target.value)}
                    onPressEnter={onSubmit}
                    style={{ marginTop: 16 }}
                />
                <Button type="primary" block loading={loading} onClick={onSubmit} style={{ marginTop: 16 }}>
                    登录
                </Button>
            </Card>
        </div>
    );
}
