import { Button, Image } from '@tarojs/components';
import Taro, { useLoad } from '@tarojs/taro';

import { Arrow } from '@taroify/icons';
import { Fragment, useCallback, useEffect, useMemo, useRef, useState } from 'react';

import { EventName, OpenSource, PageUrl } from '@/constants/app';
import { CITY_CODE_TO_NAME_MAP } from '@/constants/city';
import useLocation from '@/hooks/use-location';
import useUserInfo from '@/hooks/use-user-info';
import { StaffInfo } from '@/types/partner';
import { copy } from '@/utils/common';
import { getStaffInfo } from '@/utils/partner';
import { getPageQuery, navigateTo } from '@/utils/route';
import './index.less';

const PREFIX = 'invite-operations';

export default function InviteOperations() {
  const location = useLocation();
  const userInfo = useUserInfo();
  const [cityCode, setCityCode] = useState<string>();
  const [staffInfo, setStaffInfo] = useState<StaffInfo | null>(null);
  const [isCompany, setIsCompany] = useState<boolean | null>(null);

  const copyText = useMemo(() => {
    return isCompany
      ? `我的播络ID是：${userInfo.userId}，邀你进主播群【企业】`
      : `我的播络ID是：${userInfo.userId}，邀你进群`;
  }, [userInfo.userId, isCompany]);

  const handleClickCityMenu = useCallback(() => {
    navigateTo(PageUrl.CitySearch, { city: cityCode || location.cityCode, source: OpenSource.InviteOperations });
  }, [cityCode, location.cityCode]);

  const handleCityChange = useCallback(data => {
    console.log('handleCityChange', data);
    const { openSource, cityCode: cCode } = data;
    if (openSource !== OpenSource.InviteOperations) {
      return;
    }
    setCityCode(cCode);
  }, []);

  const handleCopy = useCallback(() => {
    copy(copyText);
  }, [copyText]);

  useEffect(() => {
    Taro.eventCenter.on(EventName.SELECT_CITY, handleCityChange);
    return () => {
      Taro.eventCenter.off(EventName.SELECT_CITY, handleCityChange);
    };
  }, [handleCityChange]);

  const useCopyRef = useRef(false);

  useEffect(() => {
    if (!userInfo.userId) return;
    if (isCompany === null) return;
    if (useCopyRef.current) return;
    handleCopy();
    useCopyRef.current = true;
  }, [handleCopy, isCompany, userInfo.userId]);

  useEffect(() => {
    if (!cityCode) return;

    getStaffInfo(cityCode)
      .then(data => {
        setStaffInfo(data);
      })
      .catch(() => {
        setStaffInfo(null);
      });
  }, [cityCode]);

  useLoad(async () => {
    const query = getPageQuery<{ company: number }>();
    setIsCompany(typeof query.company !== 'undefined');
  });

  return (
    <div className={PREFIX}>
      <div className={`${PREFIX}__main`}>
        <div className={`${PREFIX}__block`}>
          <div className={`${PREFIX}__lined-wrapper`}>
            <div className={`${PREFIX}__lined-title ${PREFIX}__title`}>活动说明</div>
          </div>
          <div className={`${PREFIX}__card`}>
            <div className={`${PREFIX}__h1 center`}>邀请播络运营进带货主播群</div>
            <div className={`${PREFIX}__h1 center`} style={{ paddingBottom: `48rpx` }}>
              {isCompany ? '每邀请进10个群送一个企业月会员' : '每邀请进一个群送一个日会员'}
            </div>
            <div className={`${PREFIX}__edging`}>注：只能邀请带货主播群，请勿邀请其他群</div>
          </div>
        </div>
        <div className={`${PREFIX}__block`}>
          <div className={`${PREFIX}__lined-wrapper`}>
            <div className={`${PREFIX}__lined-title ${PREFIX}__title`}>邀请方法</div>
          </div>
          <div className={`${PREFIX}__card`}>
            <div className={`${PREFIX}__body`}>
              <div className={`${PREFIX}__h1`}>
                加运营为好友并将以下信息 <div className="highlight">粘贴发送给运营</div>
              </div>
              <div className={`${PREFIX}__action-block`}>
                <div>{copyText}</div>
                <Button className={`${PREFIX}__copy`} onClick={handleCopy}>
                  复制
                </Button>
              </div>
              <div className={`${PREFIX}__lined-wrapper`}>
                <div className={`${PREFIX}__lined-title`}>选择城市，添加运营</div>
              </div>
              <div className={`${PREFIX}__city-select`} onClick={handleClickCityMenu}>
                {cityCode ? CITY_CODE_TO_NAME_MAP.get(cityCode) : '请选择城市'}
                <Arrow size={16} />
              </div>
              {staffInfo && (
                <Fragment>
                  <div className={`${PREFIX}__lined-wrapper`}>
                    <div className={`${PREFIX}__lined-title`}>长按并识别二维码添加运营</div>
                  </div>
                  <Image
                    className={`${PREFIX}__qrcode`}
                    src={staffInfo.staffQrCode}
                    showMenuByLongpress
                    mode="aspectFill"
                  />
                </Fragment>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
