import { Image } from '@tarojs/components';
import { NodesRef, useDidShow } from '@tarojs/taro';

import { ArrowUp, ArrowDown } from '@taroify/icons';
import classNames from 'classnames';
import { useCallback, useState } from 'react';

import GroupList, { IGroupListProps } from '@/components/group-list';
import Overlay from '@/components/overlay';
import ProductGroupDialog from '@/components/product-dialog/group';
import SearchInput from '@/components/search';
import Select from '@/components/select';
import { APP_TAB_BAR_ID } from '@/constants/app';
import { GROUP_STATUS_OPTIONS, GroupStatus, GroupType } from '@/constants/group';
import useListHeight, { IUseListHeightProps } from '@/hooks/use-list-height';
import { GroupInfo } from '@/types/group';
import { logWithPrefix } from '@/utils/common';

import './index.less';

interface IProps {
  type: GroupType;
}

const PREFIX = 'group-fragment';
const LIST_CONTAINER_CLASS = `${PREFIX}__list-container`;
const CALC_LIST_PROPS: IUseListHeightProps = {
  selectors: [`.${LIST_CONTAINER_CLASS}`, `#${APP_TAB_BAR_ID}`],
  calc: (rects: [NodesRef.BoundingClientRectCallbackResult, NodesRef.BoundingClientRectCallbackResult]) => {
    const [rect, diffRect] = rects;
    return diffRect.top - rect.top;
  },
};

const log = logWithPrefix(PREFIX);

const NoGroupTips = (props: { className?: string; height?: number }) => {
  const { className, height } = props;
  return (
    <div className={classNames(`${PREFIX}__tips-container`, className)} style={height ? { height } : undefined}>
      <Image className={`${PREFIX}__empty-box`} src={require('@/statics/svg/empty-box.svg')} mode="aspectFit" />
      <div className={`${PREFIX}__tips-title`}>您还没有播络邀请的群</div>
    </div>
  );
};

function ListWrapper(props: IGroupListProps) {
  const { className, listHeight, type } = props;
  const [isEmpty, setIsEmpty] = useState(false);

  const handleListEmpty = useCallback(() => {
    if (type !== GroupType.Joined) {
      return;
    }
    setIsEmpty(true);
  }, [type]);

  useDidShow(() => {
    if (!isEmpty) {
      return;
    }
    setIsEmpty(false);
  });

  if (isEmpty) {
    return <NoGroupTips className={className} height={listHeight} />;
  }

  return <GroupList {...props} onListEmpty={handleListEmpty} />;
}

function GroupFragment(props: IProps) {
  const { type } = props;
  const listHeight = useListHeight(CALC_LIST_PROPS);
  const [value, setValue] = useState<string>('');
  const [keyWord, setKeyWord] = useState<string>('');
  const [status, setStatus] = useState<GroupStatus>(GroupStatus.All);
  const [showStatusSelect, setShowStatusSelect] = useState<boolean>(false);
  const [groupInfo, setGroupInfo] = useState<GroupInfo | null>(null);

  const handleClickSearch = useCallback(() => {
    log('handleClickSearch', value);
    if (value === keyWord) {
      return;
    }
    setKeyWord(value);
  }, [value, keyWord]);

  const handleSearchClear = useCallback(() => {
    setValue('');
    setKeyWord('');
  }, []);

  const handleSearchChange = useCallback(e => setValue(e.detail.value), []);

  const handleClickStatusSelect = useCallback(() => {
    setShowStatusSelect(!showStatusSelect);
  }, [showStatusSelect]);

  const handleHideStatusSelect = useCallback(() => setShowStatusSelect(false), []);

  const handleSelectStatus = useCallback((newStatus: GroupStatus) => {
    log('handleSelectStatus', newStatus);
    setStatus(newStatus);
    setShowStatusSelect(false);
  }, []);

  const handleClickInvite = useCallback((info: GroupInfo) => {
    log('handleClickInvite', info);
    setGroupInfo(info);
  }, []);

  return (
    <div className={`${PREFIX}__container`}>
      <div className={`${PREFIX}__search-wrapper`}>
        <SearchInput
          value={value}
          placeholder="搜索群名"
          className={`${PREFIX}__search`}
          onClear={handleSearchClear}
          onSearch={handleClickSearch}
          onChange={handleSearchChange}
        />
        {type === GroupType.All && (
          <div className={classNames(`${PREFIX}__status-select`)} onClick={handleClickStatusSelect}>
            <div className="title">申请状态</div>
            {showStatusSelect ? <ArrowUp /> : <ArrowDown />}
          </div>
        )}
      </div>
      <div className={`${PREFIX}__list-wrapper`}>
        <ListWrapper
          type={type}
          status={status}
          imGroupNick={keyWord}
          listHeight={listHeight}
          className={LIST_CONTAINER_CLASS}
          onClickInvite={handleClickInvite}
        />
      </div>
      <div className={`${PREFIX}__dialog-wrapper`}>
        {groupInfo && (
          <ProductGroupDialog
            style={{ left: '25%' }}
            blGroupId={groupInfo.blGroupId}
            onClose={() => setGroupInfo(null)}
          />
        )}
      </div>
      <Overlay
        visible={showStatusSelect}
        onClickOuter={handleHideStatusSelect}
        outerClassName={`${PREFIX}__overlay-outer`}
        innerClassName={`${PREFIX}__overlay-inner`}
      >
        <Select title="申请状态" value={status} options={GROUP_STATUS_OPTIONS} onSelect={handleSelectStatus} />
      </Overlay>
    </div>
  );
}

export default GroupFragment;
