import { useLoad } from '@tarojs/taro';

import { useState } from 'react';

import PageLoading from '@/components/page-loading';
import SafeBottomPadding from '@/components/safe-bottom-padding';
import { SimpleGroupInfo } from '@/types/group';
import { requestSimpleGroupList } from '@/utils/group';
import { getPageQuery } from '@/utils/route';
import Toast from '@/utils/toast';

import './index.less';

const PREFIX = 'page-group-list';

export default function GroupList() {
  const [loading, setLoading] = useState(true);
  const [groupList, setGroupList] = useState<SimpleGroupInfo[]>([]);

  useLoad(async () => {
    try {
      const query = getPageQuery<{ city: string }>();
      const { city: cityCode } = query;
      if (!cityCode) {
        return;
      }
      const groups = await requestSimpleGroupList(cityCode);
      setLoading(false);
      setGroupList(groups);
    } catch (e) {
      Toast.error('加载失败请重试');
    }
  });

  if (loading) {
    return <PageLoading />;
  }

  return (
    <div className={PREFIX}>
      {groupList.map(group => (
        <div className={`${PREFIX}__group-card`} key={group.blGroupId}>
          {group.imGroupNick}
        </div>
      ))}
      <SafeBottomPadding />
    </div>
  );
}
