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

import { useCallback, useState } from 'react';

import LoginDialog from '@/components/login-dialog';
import { PageUrl } from '@/constants/app';
import useUserInfo from '@/hooks/use-user-info';
import { becomePartner, getPartnerBannerClose, setPartnerBannerClose } from '@/utils/partner';
import { navigateTo } from '@/utils/route';
import { isNeedPhone } from '@/utils/user';
import './index.less';

const PREFIX = 'partner-fragment-banner';

export default function PartnerBanner() {
  const userInfo = useUserInfo();
  const needPhone = isNeedPhone(userInfo);
  const isPartner = userInfo.isPartner;

  const [visible, setVisible] = useState(false);
  const [bannerClose, setBannerClose] = useState<boolean>(getPartnerBannerClose());

  const handlePartnerBannerClose = useCallback(e => {
    e.preventDefault();
    e.stopPropagation();
    setBannerClose(true);
    setPartnerBannerClose();
  }, []);

  const handleBind = useCallback(async () => {
    if (!isPartner) {
      await becomePartner();
    }
    await navigateTo(PageUrl.Partner);
  }, [isPartner]);

  const handleClick = useCallback(async () => {
    if (needPhone) {
      return;
    }
    await handleBind();
  }, [handleBind, needPhone]);

  if (bannerClose) {
    return null;
  }

  return (
    <>
      <div className={PREFIX} onClick={handleClick}>
        <Image
          className={`${PREFIX}__image`}
          src="https://publiccdn.neighbourhood.com.cn/img/partner_banner.png"
          mode="scaleToFill"
        />
        {needPhone && (
          <Button className={`${PREFIX}__btn`} onClick={() => setVisible(true)}>
            placeholder
          </Button>
        )}
        <div className={`${PREFIX}__close`} onClick={handlePartnerBannerClose} />
      </div>
      {visible && (
        <LoginDialog onCancel={() => setVisible(false)} onSuccess={handleBind} needPhone={needPhone} />
      )}
    </>
  );
}
