import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { Box, Stack, TextField, Button, Typography, Alert } from "@mui/material";
import { adminLogin } from "../../lib/adminApi";
import { setAdminToken } from "../../lib/adminAuth";
import { ADMIN_BASE } from "../../lib/config";

export default function AdminLogin() {
    const nav = useNavigate();
    const [username, setU] = useState(""); const [password, setP] = useState("");
    const [err, setErr] = useState<string | null>(null);

    async function onSubmit(e: React.FormEvent) {
        e.preventDefault();
        try {
            const { access_token } = await adminLogin(username, password);
            setAdminToken(access_token);
            nav(`${ADMIN_BASE}/users`, { replace: true });
        } catch (e:any) { setErr(e?.message || "로그인 실패"); }
    }

    return (
        <Box maxWidth={360} m="64px auto">
            <Typography variant="h5" mb={2}>관리자 로그인</Typography>
            <Box component="form" onSubmit={onSubmit}>
                <Stack spacing={2}>
                    <TextField label="아이디" value={username} onChange={e=>setU(e.target.value)} required />
                    <TextField label="비밀번호" type="password" value={password} onChange={e=>setP(e.target.value)} required />
                    <Button type="submit" variant="contained">로그인</Button>
                    {err && <Alert severity="error">{err}</Alert>}
                </Stack>
            </Box>
        </Box>
    );
}
