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

import { useCallback, useState } from 'react';

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

const PREFIX = 'partner-fragment-entry';

type JoinEntryProps = {
  onBindSuccess: () => void;
};
function JoinEntry({ onBindSuccess }: JoinEntryProps) {
  const userInfo = useUserInfo();
  const needPhone = isNeedPhone(userInfo);
  const [visible, setVisible] = useState(false);

  return (
    <>
      <div className={`${PREFIX}__join`}>
        <div className={`${PREFIX}__join-title`}>
          加入播络合伙人，高达<span className="highlight">75%</span>分成
        </div>
        <div className={`${PREFIX}__join-desc`}>模式简单，分成比例高，欢迎各位群主、经纪人或机构</div>
        {!needPhone && (
          <Button className={`${PREFIX}__join-button`} onClick={onBindSuccess}>
            立即加入
          </Button>
        )}
        {needPhone && (
          <Button className={`${PREFIX}__join-button`} onClick={() => setVisible(true)}>
            立即加入
          </Button>
        )}
      </div>
      {visible && <LoginDialog onCancel={() => setVisible(false)} onSuccess={onBindSuccess} needPhone={needPhone} />}
    </>
  );
}

export default function PartnerEntry() {
  const userInfo = useUserInfo();

  const handleBindSuccess = useCallback(async () => {
    await becomePartner();
    await requestUserInfo();
    await navigateTo(PageUrl.Partner);
  }, []);

  if (userInfo.isPartner) {
    return <PartnerKanban simple />;
  }
  return <JoinEntry onBindSuccess={handleBindSuccess} />;
}
