import Taro from '@tarojs/taro';

import { Dialog } from '@taroify/core';
import React, { useCallback, useEffect, useRef, useState } from 'react';

import { DialogStatus, PREFIX } from '@/components/product-dialog/const';
import QrCodeContent from '@/components/product-dialog/steps-ui/common-qr-code';
import GroupBuy from '@/components/product-dialog/steps-ui/group-buy';
import GroupBuySuccess from '@/components/product-dialog/steps-ui/group-buy-success';
import ConfirmContent from '@/components/product-dialog/steps-ui/group-confirm';
import GroupNeedBuyContent from '@/components/product-dialog/steps-ui/group-need-buy';
import { ProductType, QrCodeType } from '@/constants/product';
import { GroupDetail } from '@/types/group';
import { copy } from '@/utils/common';
import { getInviteGroupText, requestGroupDetail } from '@/utils/group';
import { requestProductBalance, requestProductUseRecord, requestUseProduct } from '@/utils/product';
import Toast from '@/utils/toast';

import '../index.less';

interface IProps {
  blGroupId: string;
  style?: React.CSSProperties;
  onClose: (opened: boolean) => void;
}

const PRODUCT_CODE = ProductType.AddGroup;

function ProductGroupDialog(props: IProps) {
  const { style, blGroupId, onClose } = props;
  const [status, setStatus] = useState<DialogStatus>(DialogStatus.LOADING);
  const [unlockTime, setUnlockTime] = useState(0);
  const [groupDetail, setGroupDetail] = useState<GroupDetail | null>(null);
  const initRef = useRef(() => {});

  const handleCloseDialog = useCallback(() => {
    onClose(false);
  }, [onClose]);

  const handleClickUnable = useCallback(async () => setStatus(DialogStatus.GROUP_BUY), []);

  const handleClickConfirm = useCallback(async () => {
    if (!groupDetail) {
      return;
    }
    try {
      const text = getInviteGroupText(groupDetail);
      await Promise.all([
        await copy(text),
        await requestUseProduct(PRODUCT_CODE, { blGroupId: groupDetail.blGroupId }),
      ]);
      setStatus(DialogStatus.GROUP_QR_CODE);
    } catch (e) {
      Toast.error('出错了，请重试');
    }
  }, [groupDetail]);

  const handleClickBuy = useCallback(async (time: number) => {
    setUnlockTime(time);
    setStatus(DialogStatus.GROUP_BUY_SUCCESS);
  }, []);

  const handleClickBuySuccess = useCallback(async () => {
    setStatus(DialogStatus.GROUP_CONFIRM_ADD);
  }, []);

  useEffect(() => {
    initRef.current = async () => {
      // if (1 < 2) {
      //   setStatus(DialogStatus.GROUP_BUY);
      //   return;
      // }
      try {
        Taro.showLoading();
        // 当前群之前解锁过，直接显示二维码页面
        const result = await requestProductUseRecord(PRODUCT_CODE, { blGroupId });
        if (result) {
          const detail = await requestGroupDetail(blGroupId);
          const text = getInviteGroupText(detail);
          await copy(text);
          setStatus(DialogStatus.GROUP_QR_CODE);
          return;
        }
        // 否则：如果有解锁次数，显示是否确定消费。无解锁次数，显示不无次数 UI
        const [[time], detail] = await Promise.all([
          requestProductBalance(PRODUCT_CODE),
          requestGroupDetail(blGroupId),
        ]);
        setGroupDetail(detail);
        if (time <= 0) {
          setStatus(DialogStatus.GROUP_NEED_BUY_ADD);
        } else {
          setUnlockTime(time);
          setStatus(DialogStatus.GROUP_CONFIRM_ADD);
        }
      } catch (e) {
        Toast.error('出错了，请重试');
        handleCloseDialog();
      } finally {
        Taro.hideLoading();
      }
    };
  }, [blGroupId, handleCloseDialog]);

  useEffect(() => {
    initRef.current();
  }, []);

  if (status === DialogStatus.LOADING) {
    return null;
  }

  return (
    <Dialog className={PREFIX} onClose={onClose} style={style} open>
      <Dialog.Content>
        {status === DialogStatus.GROUP_NEED_BUY_ADD && <GroupNeedBuyContent onConfirm={handleClickUnable} />}
        {status === DialogStatus.GROUP_CONFIRM_ADD && (
          <ConfirmContent unlockTime={unlockTime} onConfirm={handleClickConfirm} />
        )}
        {status === DialogStatus.GROUP_QR_CODE && <QrCodeContent type={QrCodeType.Group} />}
        {status === DialogStatus.GROUP_BUY && <GroupBuy source="group-list" onConfirm={handleClickBuy} />}
        {status === DialogStatus.GROUP_BUY_SUCCESS && (
          <GroupBuySuccess unlockTime={unlockTime} onConfirm={handleClickBuySuccess} />
        )}
      </Dialog.Content>
    </Dialog>
  );
}

export default ProductGroupDialog;
