import { Button, Form, Input, Modal, message } from "antd";
import api from "../api";

interface Props {
  open: boolean;
  onSuccess: () => void;
}

export default function LoginModal({ open, onSuccess }: Props) {
  const [form] = Form.useForm();

  const onFinish = async (values: { username: string; password: string }) => {
    try {
      const { data } = await api.post("/auth/login", values);
      localStorage.setItem("pb_token", data.access_token);
      message.success("登录成功");
      onSuccess();
    } catch {
      message.error("登录失败，请检查用户名或密码");
    }
  };

  return (
    <Modal open={open} title="管理员登录" footer={null} closable={false} maskClosable={false}>
      <Form form={form} layout="vertical" onFinish={onFinish}>
        <Form.Item label="用户名" name="username" rules={[{ required: true }]}>
          <Input placeholder="admin" />
        </Form.Item>
        <Form.Item label="密码" name="password" rules={[{ required: true }]}>
          <Input.Password />
        </Form.Item>
        <Button type="primary" htmlType="submit" block>
          登录
        </Button>
      </Form>
    </Modal>
  );
}
