"use client";

import { GoDeviceMobile, GoLock } from "react-icons/go";
import { LoginForm, ProForm, ProFormCaptcha, ProFormText } from "@ant-design/pro-components";
import { Alert, message, Tabs } from "antd";
import React, { useState } from "react";
import styles from "./login.module.scss";
import { login, sendCaptcha } from "@/lib/user";

import { useRouter } from "next/navigation";
import Cookies from "js-cookie";
import { useCommonContext } from "@/context/commonContext";
// import { useModel } from "@@/plugin-model/useModel";
// import { USER_TYPE_ADMIN, USER_TYPE_PLATFORM } from "@/services/constants";

type LoginParams = {
  type?: number;
  username?: string;
  password?: string;
  captcha?: string;
  sourceId?: number;
};

const LoginMessage: React.FC<{ content: string }> = ({ content }) => (
  <Alert
    style={{
      marginBottom: 24,
    }}
    message={content}
    type="error"
    showIcon
  />
);

export default function Login() {
  const router = useRouter();
  const [errorMsg, setErrorMsg] = useState<string>("");
  const [type, setType] = useState<string>("password");
  const [form] = ProForm.useForm();
  const { redirectAfterLogin, setUser } = useCommonContext();

  const handleSubmit = async (values: LoginParams) => {
    try {
      const response = await login({ ...values, type: type == "password" ? 0 : 1 });
      if (response.code === 200) {
        const data = response.data;
        Cookies.set("ut", data.token);

        const user = {
          id: data.id,
          name: data.name,
          phone: data.phone,
        };
        setUser(user);
        router.push(redirectAfterLogin);
        return;
      }
      setErrorMsg(response.message || "");
    } catch (error) {
      console.log(error);
      message.error("登录失败，请重试！");
    }
  };

  const tabItems = [
    {
      key: "password",
      label: "手机号密码登录",
    },
    {
      key: "captcha",
      label: "手机号验证码登录",
    },
  ];

  return (
    <div className={styles.container}>
      <div className={styles.content}>
        <LoginForm
          form={form}
          title="高潜咨询"
          subTitle={"中国企业人效的未来"}
          initialValues={{}}
          actions={[]}
          onFinish={async (values) => {
            await handleSubmit(values as LoginParams);
          }}
        >
          <Tabs activeKey={type} onChange={setType} items={tabItems} />

          {errorMsg && <LoginMessage content={errorMsg} />}

          {type === "password" && (
            <>
              <ProFormText
                fieldProps={{
                  size: "large",
                  prefix: <GoDeviceMobile className={styles.prefixIcon} />,
                }}
                name="phone"
                placeholder="手机号"
                rules={[
                  {
                    required: true,
                    message: "请输入手机号！",
                  },
                  {
                    pattern: /^1\d{10}$/,
                    message: "手机号格式错误！",
                  },
                ]}
              />
              <ProFormText.Password
                name="password"
                fieldProps={{
                  size: "large",
                  prefix: <GoLock className={styles.prefixIcon} />,
                }}
                placeholder={"密码"}
                rules={[
                  {
                    required: true,
                    message: "请输入密码",
                  },
                ]}
              />
            </>
          )}

          {type === "captcha" && (
            <>
              <ProFormText
                fieldProps={{
                  size: "large",
                  prefix: <GoDeviceMobile className={styles.prefixIcon} />,
                }}
                name="phone"
                placeholder="手机号"
                rules={[
                  {
                    required: true,
                    message: "请输入手机号！",
                  },
                  {
                    pattern: /^1\d{10}$/,
                    message: "手机号格式错误！",
                  },
                ]}
              />
              <ProFormCaptcha
                fieldProps={{
                  size: "large",
                  prefix: <GoLock className={styles.prefixIcon} />,
                }}
                captchaProps={{
                  size: "large",
                }}
                placeholder="请输入验证码"
                captchaTextRender={(timing, count) => {
                  if (timing) {
                    return `${count} 获取验证码`;
                  }
                  return "获取验证码";
                }}
                name="captcha"
                rules={[
                  {
                    required: true,
                    message: "请输入验证码！",
                  },
                ]}
                onGetCaptcha={async () => {
                  const phone = form.getFieldValue("phone");
                  if (!phone) {
                    message.error("请先输入手机号");
                    throw new Error("请先输入手机号");
                  }
                  const result = await sendCaptcha(phone);
                  if (result === false) {
                    return;
                  }
                  message.success("获取验证码成功");
                }}
              />
            </>
          )}
          <div
            style={{
              marginBottom: 24,
            }}
          ></div>
        </LoginForm>
      </div>
      <div className={styles.footer}>@2024 高潜咨询</div>
    </div>
  );
}
