import { useState, type Dispatch, type FC, type SetStateAction } from "react";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogTitle,
} from "./ui/dialog";
import { Input } from "./ui/input";
import { Button } from "./ui/button";
import { LoginApi, MeApi } from "@/api";
import { message } from "@/utils/message";
import { useUserStore } from "@/stores";

interface LoginProps {
  className?: string;
  isOpen: boolean;
  setIsOpen: Dispatch<SetStateAction<boolean>>;
}

const Login: FC<LoginProps> = ({ className = "", isOpen, setIsOpen }) => {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const { user, setUser } = useUserStore();

  const handlerLogin = async () => {
    // console.log(username, password);
    const data = { username, password };

    const res = await LoginApi({ data });
    if (res.code === 0) {
      const res2 = await MeApi({});
      if (res2.code !== 0) {
        message(res2.msg);
        return;
      }
      setUser(res2.data);
      setIsOpen(false);
      setUsername("");
      setPassword("");
      message("登录成功！");
    } else {
      message(res.msg);
    }
  };

  return (
    <div className={className}>
      <Dialog open={isOpen} onOpenChange={() => setIsOpen(!isOpen)}>
        <DialogContent>
          <DialogTitle>Login View</DialogTitle>
          <DialogDescription></DialogDescription>
          <div className="flex-row flex items-center space-x-4">
            <span className="flex-1">用户名: </span>
            <Input
              className="flex-7"
              autoComplete="off"
              id="username"
              value={username}
              onChange={(e) => setUsername(e.target.value)}
              placeholder="请输入用户名"
            />
          </div>
          <div className="flex-row flex items-center space-x-4">
            <span className="flex-1">密码: </span>
            <Input
              className="flex-7"
              autoComplete="off"
              id="password"
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              placeholder="请输入密码"
            />
          </div>
          <Button className="mt-5" onClick={handlerLogin}>
            登录
          </Button>
        </DialogContent>
      </Dialog>
    </div>
  );
};

export default Login;
