import { Login } from "../api/login";
import { setLocalStorage } from "../utils/local";
import { LockOutlined, UserOutlined } from "@ant-design/icons";
import { Form, Space, Typography, Button, Input } from "antd";
// import GoCaptcha from "go-captcha-react";
import React, { useEffect } from "react";
import { LoginReq } from "../types/login";
import { useMutation } from "@tanstack/react-query";
import { useNavigate, useSearchParams } from "react-router-dom";

const View: React.FC = () => {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();

  // 从URL参数中获取值，如果不存在则使用空字符串
  const isAutoLogin = searchParams.get("isAutoLogin") || "";
  const username = searchParams.get("username") || "";
  const password = searchParams.get("password") || "";
  const [form] = Form.useForm();
  const title = "录像同步";

  useEffect(() => {
    document.title = title;
  }, []);

  useEffect(() => {
    // 只有当username或password有值时，才更新表单
    if (username || password) {
      form.setFieldsValue({
        username: username || undefined,
        password: password || undefined,
      });

      // 如果启用了自动登录且有用户名和密码，则自动提交
      if (isAutoLogin && username && password) {
        form.submit();
      }
    }
  }, [username, password, isAutoLogin, form]);

  const { mutate, isPending } = useMutation({
    mutationFn: Login,
    onSuccess: (res) => {
      setLocalStorage("token", res.data.token);
      navigate("/home");
    },
    onError: (err) => {
      form.setFieldsValue({ captcha: "" });
      ErrorHandle(err);
    },
  });

  //   const { data: captchaData, refetch } = useQuery<CaptchaRes>({
  //     queryKey: [getCaptcha],
  //     queryFn: () =>
  //       GetCaptcha()
  //         .then((res) => res.data)
  //         .catch((err) => {
  //           ErrorHandle(err);
  //           throw err;
  //         }),
  //     refetchInterval: 280000,
  //   });

  //   const [captchaEnabled, setCaptchaEnabled] = useState(false);
  return (
    <div className="h-screen overflow-auto bg-[url('https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/V-_oS6r-i7wAAAAAAAAAAAAAFl94AQBr')] bg-cover">
      <div
        style={{ minWidth: "300px", maxWidth: "350px", marginTop: 32 }}
        className="py-8 relative top-[30%] left-1/2 -translate-y-1/2 -translate-x-1/2"
      >
        <Form
          form={form}
          className=" text-center"
          onFinish={async (values: Omit<LoginReq, "captcha_id">) => {
            // if (
            //   captchaData &&
            //   captchaData.captcha_id !== 0 &&
            //   !values.captcha?.trim()
            // ) {
            //   form
            //     .validateFields(["username", "password"])
            //     .then(() => {
            //       setCaptchaEnabled(true);
            //     })
            //     .catch((err) => {
            //       console.error("验证失败", err);
            //     });
            //   return;
            // }

            mutate({
              username: values.username.trim(),
              password: values.password.trim(),
              captcha: values.captcha?.trim() ?? "",
              captcha_id: 0,
            });
          }}
        >
          <Space className="mb-7 pb-3" align="center">
            <Typography.Title style={{ marginBottom: 0 }} level={3}>
              {title}
            </Typography.Title>
          </Space>

          <div className="text-left">
            <Form.Item
              name="username"
              rules={[{ required: true, message: "请输入用户名" }]}
            >
              <Input
                size="large"
                prefix={<UserOutlined />}
                placeholder="用户名"
              />
            </Form.Item>
            <Form.Item
              name="password"
              rules={[{ required: true, message: "请输入密码" }]}
            >
              <Input.Password
                size="large"
                prefix={<LockOutlined />}
                placeholder="密码"
              />
            </Form.Item>
            <Form.Item
              hidden
              name="captcha"
              rules={[{ required: false, message: "请完成验证码" }]}
            >
              <Input size="large" placeholder="验证码" />
            </Form.Item>
          </div>

          <Button
            loading={isPending}
            type="primary"
            style={{ width: "100%" }}
            htmlType="submit"
            size="large"
            onClick={() => {
              // 如果账号密码为空自动填充上admin
              if (
                !form.getFieldValue("username") ||
                !form.getFieldValue("password")
              ) {
                form.setFieldsValue({
                  username: "admin",
                  password: "admin",
                });
              }
            }}
          >
            登录
          </Button>
        </Form>
      </div>
    </div>
  );
};

export default View;
function ErrorHandle(err: Error) {
  throw new Error("Function not implemented.");
}
