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

import { Popup } from '@taroify/core';
import { useCallback, useEffect, useState } from 'react';

import PhoneButton, { BindPhoneStatus, IPhoneButtonProps } from '@/components/phone-button';
import { ProtocolPrivacyCheckbox } from '@/components/protocol-privacy';
import SafeBottomPadding from '@/components/safe-bottom-padding';
import useUserInfo from '@/hooks/use-user-info';
import { logWithPrefix, sleep } from '@/utils/common';
import { waitLocationAuthorizeHidden } from '@/utils/location';
import Toast from '@/utils/toast';
import { shouldShowLoginGuide } from '@/utils/user';

import './index.less';

interface IContentProps extends Pick<IPhoneButtonProps, 'onBindPhone'> {
  onCancel: () => void;
}

interface IProps {
  disabled: boolean;
  onAfterBind?: () => void;
}

const PREFIX = 'login-content';
const PREFIX_GUIDE = 'login-guide';
const log = logWithPrefix(PREFIX_GUIDE);

function LoginContent(props: IContentProps) {
  const { onCancel, onBindPhone } = props;
  const [checked, setChecked] = useState(false);

  const handleClose = useCallback(() => onCancel(), [onCancel]);

  const handleTipCheck = useCallback(() => {
    Toast.info('请先阅读并同意协议');
  }, []);

  return (
    <div className={`${PREFIX}__container`}>
      <div className={`${PREFIX}__title`}>使用播络服务前，请先登录</div>
      {!checked && (
        <Button className={`${PREFIX}__confirm-button`} onClick={handleTipCheck}>
          登录
        </Button>
      )}
      {checked && (
        <PhoneButton
          className={`${PREFIX}__confirm-button`}
          onSuccess={handleClose}
          onBindPhone={onBindPhone}
          needPhone
        >
          登录
        </PhoneButton>
      )}
      <Button className={`${PREFIX}__cancel-button`} onClick={handleClose}>
        跳过，暂不登录
      </Button>
      <ProtocolPrivacyCheckbox checked={checked} onChange={setChecked} className={`${PREFIX}__checkbox`} />
    </div>
  );
}

export function LoginGuide(props: IProps) {
  const { disabled = false, onAfterBind } = props;
  const userInfo = useUserInfo();
  const [open, setOpen] = useState(false);

  const handleBind = useCallback(
    (status: BindPhoneStatus) => {
      status === BindPhoneStatus.Success && onAfterBind?.();
      status === BindPhoneStatus.Success && setOpen(false);
    },
    [onAfterBind]
  );

  const handleClose = useCallback(() => setOpen(false), []);

  useEffect(() => {
    if (disabled || !shouldShowLoginGuide(userInfo)) {
      return;
    }
    let effectCleaned = false;
    const showGuide = async () => {
      await sleep(1);
      await waitLocationAuthorizeHidden();
      if (effectCleaned) {
        log('ignore login guide, effect changed');
        return;
      }
      setOpen(true);
      log('open login guide');
    };
    showGuide();
    return () => {
      effectCleaned = true;
    };
  }, [disabled, userInfo]);

  useEffect(() => {
    if (disabled) {
      log('hide login guide by disabled');
      setOpen(false);
    }
  }, [disabled]);

  if (!open) {
    return null;
  }

  return (
    <Popup className={PREFIX_GUIDE} placement="bottom" open={open} onClose={handleClose}>
      <LoginContent onCancel={handleClose} onBindPhone={handleBind} />
      <SafeBottomPadding />
    </Popup>
  );
}
