import React, { useContext, useState, useCallback } from "react";
import {
  Button,
  Box,
  Radio,
  FormControlLabel,
  RadioGroup,
  Typography,
  InputAdornment,
  TextField,
  FormControl,
  Alert,
} from "@mui/material";
import PageLayout from "../../../Common/Layout/PageLayout";
import PageHeader from "../../../Common/PageHeader/PageHeader";
import AlipayImg from "../../assets/alipay.jpeg";
import WechatImg from "../../assets/wechat.png";
import OfflineImg from "../../assets/offline.png";
import { createOrder } from "../../services";
import { CreateOrderRequestBody } from "../../services/interface";
import { PAY, PAY_TYPE } from "../../constants";
import Modal from "../../components/Modal";

import styles from "./index.module.css";
import { UserInfoContext } from "../../context/UserInfoContext";
import { useAccountMoneyInfo } from "./hooks";
import { toNewTab } from "../../utils";

const startAdornment = <InputAdornment position="start">￥</InputAdornment>;
const payTypeList = [
  {
    cname: PAY.ALI.cname,
    value: PAY.ALI.value,
    logo: AlipayImg,
  },
  {
    cname: PAY.WECHAT.cname,
    value: PAY.WECHAT.value,
    logo: WechatImg,
  },
  {
    cname: "银联",
    value: 3,
    logo: OfflineImg,
  },
];

class OfflinePayModal {
  visible: boolean = false;
}

const CostRecharge: React.FC = () => {
  const userInfo = useContext(UserInfoContext);
  const { data: moneyInfo } = useAccountMoneyInfo();
  const [loading, setLoading] = useState(false);
  const [offlinePayModal, setOfflinePayModal] = useState<OfflinePayModal>(
    new OfflinePayModal()
  );
  const [form, setForm] = useState<CreateOrderRequestBody>({
    money: 5000,
    pay_type: 1,
  });
  const submitHandler = useCallback(
    (e) => {
      e.preventDefault();
      setLoading(true);
      createOrder(form)
        .then((res) => {
          if (form.pay_type === PAY.ALI.value) {
            toNewTab(res.data.url);
          }
          console.log(res);
        })
        .finally(() => {
          setLoading(false);
        });
    },
    [form]
  );

  function offlineModalShow() {
    setOfflinePayModal((state) => ({ ...state, visible: true }));
  }
  function offlineModalHide() {
    setOfflinePayModal((state) => ({ ...state, visible: false }));
  }
  return (
    <>
      <PageHeader label="充值"></PageHeader>
      <PageLayout>
        <div>
          <Box
            sx={{
              "& .MuiTextField-root": { mb: 3 },
            }}
            style={{ maxWidth: 500 }}
          >
            <TextField
              fullWidth
              label="充值账户"
              value={userInfo?.phone || userInfo?.email}
              InputProps={{ readOnly: true }}
            />
            <TextField
              fullWidth
              label="账户余额"
              name="money"
              value={moneyInfo.balance}
              InputProps={{ readOnly: true, startAdornment }}
            />
            <TextField
              fullWidth
              required
              label="充值金额"
              value={form.money}
              type="number"
              inputMode="numeric"
              inputProps={{ min: 5000, step: 1000 }}
              InputProps={{
                startAdornment,
              }}
              helperText="充值金额不低于5000元，且为1000的整数倍"
              onChange={(e) => {
                let value = Number(e.target.value);
                setForm((state) => ({ ...state, money: value }));
              }}
              onBlur={(e) => {
                let value = Number(e.target.value);
                if (value < 5000) {
                  value = 5000;
                }
                if (value % 1000) {
                  value -= value % 1000;
                }
                setForm((state) => ({ ...state, money: value }));
              }}
            />
            <FormControl>
              <RadioGroup
                row
                name="pay_type"
                value={form.pay_type}
                onChange={(e) => {
                  const value = Number(e.target.value) as PAY_TYPE;
                  setForm((state) => ({ ...state, pay_type: value }));
                }}
              >
                {payTypeList.map((pay) => {
                  return (
                    <FormControlLabel
                      key={pay.value}
                      value={pay.value}
                      control={<Radio />}
                      label={
                        <div className={styles.payType}>
                          <img src={pay.logo} alt="" />
                        </div>
                      }
                      onClick={() => {
                        if (pay.value === 3) {
                          offlineModalShow();
                        }
                      }}
                    />
                  );
                })}
              </RadioGroup>
            </FormControl>

            <div style={{ marginTop: 40 }}>
              <Button
                variant="contained"
                type="submit"
                disabled={loading}
                onClick={submitHandler}
              >
                充 值
              </Button>
            </div>
            {/* <Alert color="warning">
            <AlertTitle>提示</AlertTitle>
            当您在使用 Safari、QQ 等浏览器进行支付宝充值时，若出现{" "}
            <strong>弹出式窗口被阻止</strong> 请在 <strong>偏好设置</strong>中
            <strong>选择网络</strong> <span>{"-->"}</span>{" "}
            <strong>弹出式窗口</strong>
            <span>{"-->"}</span> <strong>允许</strong> 即可！
          </Alert> */}
          </Box>
          <Modal
            visible={offlinePayModal.visible}
            onCancel={offlineModalHide}
            title="支付中心"
            width={700}
          >
            <Typography>
              <p>支付方式： 暂支持转账汇款 </p>
              <p>
                银行账号：<span>0506210000000950</span>{" "}
                <small>
                  （附言中请注明土星云用户名以及您注册时留下的手机号码）
                </small>
              </p>
              <p>开户行：南京银行北京分行</p>
              <p>账户名称：北京国科环宇科技股份有限公司</p>
              <p>
                土星云客服热线：<a href="tel:4006405800">4006405800</a>
                ，客服邮箱：
                <a href="mailto:sales@saturncloud.com.cn">
                  sales@saturncloud.com.cn
                </a>
              </p>
              <Alert icon={false}>
                汇款后请第一时间联系土星云客服热线并提供汇款凭证截图，以便我们及时为您开通服务。
              </Alert>
            </Typography>
          </Modal>
        </div>
      </PageLayout>
    </>
  );
};

export default CostRecharge;
