import { Loading } from '@taroify/core';
import classNames from 'classnames';
import { useEffect, useRef, useState } from 'react';

import { ProductType } from '@/constants/product';
import { ProductInfo } from '@/types/product';
import { requestProductList } from '@/utils/product';
import Toast from '@/utils/toast';

import './index.less';

interface IProps {
  className?: string;
}

const PREFIX = 'product-card';
const getProductDescribe = (type: ProductType) => {
  switch (type) {
    case ProductType.GetJob:
      return '群通告付费联系剩余次数';
    case ProductType.AddGroup:
      return '添加定制群剩余次数';
    default:
      return '';
  }
};

function ProductCard(props: IProps) {
  const { className } = props;
  const [loading, setLoading] = useState(false);
  const [productList, setProductList] = useState<ProductInfo[]>([]);
  const initRef = useRef(() => {});

  useEffect(() => {
    initRef.current = async () => {
      try {
        setLoading(true);
        const list = await requestProductList();
        setProductList(list);
      } catch (e) {
        Toast.error('请求失败');
      } finally {
        setLoading(false);
      }
    };
  }, []);

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

  return (
    <div className={classNames(PREFIX, className)}>
      <div className={`${PREFIX}__title`}>账户信息</div>
      {productList.map((product: ProductInfo) => {
        return (
          <div className={`${PREFIX}__item-container`} key={product.productId}>
            <div className={`${PREFIX}__item-name`}>{getProductDescribe(product.productId)}</div>
            <div className={`${PREFIX}__item-balance`}>{`${product.balance}次`}</div>
          </div>
        );
      })}
      {loading && <Loading size={20} />}
    </div>
  );
}

export default ProductCard;
