import { useRequest } from "ahooks";
import { useAuthHeaders } from "../hooks/useAuthHeaders";
import { Alert, App, Button, Drawer, Flex, Form, Input, Spin, Typography } from "antd";
import { ExportOutlined, LinkOutlined } from "@ant-design/icons";
import { useCallback, useState } from "react";
import { useNavigate } from "react-router";

export const BindKaiqiuAccount = () => {
  const headers = useAuthHeaders();
  const isBindReq = useRequest<{
    isBinded: boolean;
    uid?: string;
  }, []>(async () => {
    return fetch('/api/account/bind', { headers }).then(res => res.json());
  }, { manual: false, debounceWait: 300 });
  const [open, setOpen] = useState(false);
  const [form] = Form.useForm<{ password: string, username: string }>();
  const { modal, message } = App.useApp();
  const bindRequest = useRequest(async (data) => {
    const result = await fetch('/api/account/bind', {
      method: 'PUT',
      body: JSON.stringify(data),
      headers,
    }).then(res => res.json());
    return result;
  }, { manual: true });
  const handleBind = useCallback(async () => {
    const data = await form.validateFields().catch(() => Promise.reject());
    const result = await bindRequest.runAsync(data);
    if (!result.success) {
      message.error(result.message);
      return;
    }
    await isBindReq.runAsync();
    message.success('绑定成功');
    setOpen(false);
  }, [form, headers, isBindReq, message]);
  const handleForgotPass = useCallback(() => {
    modal.info({
      title: '忘记密码',
      content: (
        <div>
          打开微信小程序 - 我的 - 修改资料 - 用户安全 - 重置密码
        </div>
      ),
    });
  }, [modal]);
  const navigate = useNavigate();
  if (isBindReq.data?.isBinded === undefined) return null;
  if (isBindReq.data?.isBinded) {
    return (
      <Flex gap={8} onClick={() => navigate(`/profile/${isBindReq.data?.uid}`)}>
        <Typography.Text type="secondary">UID: {isBindReq.data?.uid ?? '-'}</Typography.Text>
        <ExportOutlined />
      </Flex>
    );
  }
  return (
    <>
      <Button
        icon={<LinkOutlined />}
        onClick={() => setOpen(true)}
      >
        绑定开球网账号
      </Button>
      <Drawer
        title="绑定开球网账号"
        placement="bottom"
        size={500}
        open={open}
        onClose={() => setOpen(false)}
      >
        <Flex gap={12} vertical>
          <Alert type='success' description="后台不会存储账号密码，仅用于登录开球网获取数据。绑定后修改密码不影响绑定结果" />
          <Spin spinning={bindRequest.loading}>
            <Form form={form}>
              <Form.Item rules={[{ required: true, message: '' }]} label="开球网用户名" name={'username'}>
                <Input />
              </Form.Item>
              <Form.Item rules={[{ required: true, message: '' }]} label="开球网密码" name={'password'}>
                <Input.Password />
              </Form.Item>
            </Form>
          </Spin>
          <Button block type="primary" loading={bindRequest.loading} onClick={handleBind}>绑定</Button>
          <Button block type="link" onClick={handleForgotPass}>忘记密码？</Button>
        </Flex>
      </Drawer>
    </>
  );
}