import { BaseEventOrig, Button, Input, InputProps } from '@tarojs/components';

import { Cell, Popup } from '@taroify/core';
import classNames from 'classnames';
import { useCallback, useState } from 'react';

import SafeBottomPadding from '@/components/safe-bottom-padding';
import useUserInfo from '@/hooks/use-user-info';
import Toast from '@/utils/toast';
import { updateUserInfo } from '@/utils/user';

import './index.less';

interface IProps {
  className?: string;
}

const PREFIX = 'wechat-cell';

function WechatCell(props: IProps) {
  const { className } = props;
  const userInfo = useUserInfo();
  const [open, setOpen] = useState(false);
  const [value, setValue] = useState(userInfo.imAcctNo || '');
  const title = userInfo.imAcctNo ? `联系微信：${userInfo.imAcctNo}` : '尚未提供联系微信号';

  const handleClick = useCallback(() => setOpen(true), []);

  const handleInput = useCallback((e: BaseEventOrig<InputProps.inputEventDetail>) => {
    const text = e.detail.value || '';
    setValue(text);
  }, []);

  const handleSubmit = useCallback(async () => {
    if (!value) {
      Toast.error('微信号不能为空');
      return;
    }
    await updateUserInfo({ imAcctNo: value });
    setOpen(false);
  }, [value]);

  return (
    <>
      <Cell
        className={classNames(PREFIX, className, { 'no-wechat': !userInfo.imAcctNo })}
        align="center"
        title={title}
        onClick={handleClick}
        isLink
      >
        <div className={`${PREFIX}__cell_right-text`}>{userInfo.imAcctNo ? '修改' : '去提供'}</div>
      </Cell>
      <Popup className={`${PREFIX}__popup`} placement="bottom" open={open} onClose={() => setOpen(false)}>
        <div className={`${PREFIX}__popup__content`}>
          <div className={`${PREFIX}__popup__title`}>联系微信</div>
          <div className={`${PREFIX}__popup__tips`}>当与对方交换联系方式时，会优先发送以下微信号</div>
          <Input
            value={value}
            confirmType="done"
            placeholder="请输入微信号"
            onInput={handleInput}
            className={`${PREFIX}__popup__input`}
            placeholderClass={`${PREFIX}__popup__input-placeholder`}
          />
          <Button className={`${PREFIX}__popup_confirm-button`} onClick={handleSubmit}>
            保存
          </Button>
        </div>
        <SafeBottomPadding />
      </Popup>
    </>
  );
}

export default WechatCell;
