import { observer } from 'mobx-preact';
import { h } from 'preact';
import { useState, useRef } from 'preact/hooks';

import CdnImage from '../cdn-image/cdn-image';
import { useLoadMore } from '../common/hooks/use-load-more/index';
import { gImg } from '../common/i18n/image';
import { $t } from '../locale';
import PMGDropDown from '../pmg-drop-down/pmg-drop-down';
import PMGPopupContainer from '../pmg-popup-container/pmg-popup-container';

import styles from './css/index.less';

const defaultAvatar = gImg('https://cdn.partner.esports.pubgmobile.com/os-pubgm/en/pix/comp/default-teammate-avatar.png');


const PMGJoinTeamApplyDialog = (props: {
  handleSelect: (...args: any[]) => void;
  onClickClose: () => void;
  onClickCancel: (...args: any[]) => void;
  onClickConfirm: (...args: any[]) => void;

  title?: string;
  tip?: string;

  dropDownWidth?: string;
  dropDownHeight?: string;
  scrollHeight?: string;
  sidebarList?: any[];
  applyList?: any[];

  cancelBtnText?: string;
  confirmBtnText?: string;
  onLoadMore?: () => void;
  finished?: boolean;
}) => {
  const {
    onClickClose,
    onClickCancel,
    onClickConfirm,

    title = $t('入队申请'),

    dropDownWidth = '2.12rem',
    dropDownHeight = '.42rem',
    scrollHeight = '2rem',

    sidebarList,
    tip = $t('参赛后队伍成员不可再变更'),
    applyList,

    cancelBtnText,
    confirmBtnText,
    onLoadMore,
    finished,
  } = props;


  const [selectedValues, setSelectedValues] = useState<any[]>([]);
  const handleSelect = (value, index, sidebarTitle, sidebarIndex) => {
    const updatedSelectedValues = [...(selectedValues || [])];


    // 直接根据 index 更新或添加值
    updatedSelectedValues[sidebarIndex] = { sidebarTitle, value, index };

    setSelectedValues(updatedSelectedValues);

    // 组件通信
    if (props.handleSelect) {
      props.handleSelect(index, sidebarTitle, value, sidebarIndex, updatedSelectedValues);
    }
  };

  const listContainerRef = useRef(null);

  useLoadMore(
    async () => {
      onLoadMore?.();
    },
    {
      containerRef: listContainerRef,
      threshold: 100,
      debounceDelay: 0,
      isEnabled: true,
      finished,
    },
  );


  return (
    <PMGPopupContainer
      size="large"
      titleColor="#fff"
      title={title}
      onClickClose={onClickClose}
    >
      <div className={styles['pmg-join-team-apply-dialog']}>
        <div className={styles['pmg-drop-down-list-wrap']}>
          {sidebarList?.map((sidebarItem, sidebarIndex) => (
            <div
              key={`key-${sidebarIndex}`}
              className={styles['pmg-drop-down-list-item']}
            >
              <PMGDropDown
                title={selectedValues[sidebarIndex]?.value ? '' : sidebarItem.title}
                dropDownWidth={dropDownWidth}
                dropDownHeight={dropDownHeight}
                scrollHeight={scrollHeight}
                sidebar={sidebarItem.sidebar}
                selectedValue={selectedValues[sidebarIndex]?.value || ''} // 根据 item.title 获取对应的 selectedValue
                onHandleSelect={(value, index) => {
                  handleSelect(value, index, sidebarItem.title, sidebarIndex); // 传递 item.title 作为 key
                }}
              />
            </div>

          ))}
        </div>
        <div className={styles['pmg-tip']}>
          <text className={styles['pmg-tip-text']}>{tip}</text>
        </div>
        <div
          className={styles['pmg-remind-teammates-content']}
          ref={listContainerRef}
        >
          {
            applyList?.map((item, index) => (
              <div
                key={item.id || index}
                className={styles['pmg-teammate-item']}
              >
                <div className={styles['pmg-teammate-content']}>
                  <div className={styles['pmg-left-content']}>
                    <CdnImage
                      className={styles['pmg-avatar-img']}
                      src={item.avatar || defaultAvatar}
                    />
                    <div className={styles['pmg-info-wrapper']}>
                      <div className={styles['pmg-name-wrapper']}>
                        {item.sex !== undefined && (<div className={`${styles['pmg-icon-sex']} ${styles[item.sex === 0 ? 'girl' : '']}`}></div>)}
                        <text className={styles['pmg-name-text']}>{item.name || item.apply_uid}</text>
                      </div>
                      <div className={styles['pmg-level-wrapper']}>
                        {item.levelIcon && (
                          <CdnImage
                            className={styles['pmg-level-img']}
                            src={item.levelIcon}
                          />
                        )}
                        <text className={styles['pmg-level-text']}>{item.levelName}</text>
                        {item.kd && <text className={styles['pmg-kd-text']}>|</text>}
                        {item.kd && <text className={styles['pmg-kd-text']}> {$t('KD')} {item.kd}</text>}
                        {item?.isPeakMatchTopPlayer && <text className={styles['pmg-divider-text']}>|</text>}
                        {
                          item?.isPeakMatchTopPlayer && (
                          <div className={styles['pmg-tag-peak-box']}>
                            <text className={styles['pmg-tag-peak-text']}>
                              {$t('巅峰500玩家')}
                            </text>
                          </div>
                          )
                        }
                      </div>
                    </div>
                  </div>
                  <div className={styles['pmg-right-content']}>
                    {item?.time && (
                      <div className={styles['pmg-apply-time']}>
                        {item.time}<text className={styles['pmg-apply-time-text']}>{$t('申请')}</text>
                      </div>
                    )}
                    {!item.btnText && (
                      <div className={styles['pmg-btn-wrapper']}>
                        {cancelBtnText &&  (
                        <div
                          className={styles['pmg-cancel-btn']}
                          onClick={() => {
                            onClickCancel(item, index);
                          }}
                        >
                          <text>{cancelBtnText}</text>
                        </div>
                        )}
                        {confirmBtnText && (
                        <div
                          className={styles['pmg-confirm-btn']}
                          onClick={() => {
                            onClickConfirm(item, index);
                          }}
                        >
                          <text>{confirmBtnText}</text>
                        </div>
                        )}
                      </div>
                    )}
                    {item.btnText && (
                      <div className={styles['pmg-btn-text']}>
                        {item.btnText}
                      </div>
                    )}
                  </div>
                </div>
                {
                  item.message && (
                    <div className={styles['pmg-bottom-message']}>
                      <text className={styles['pmg-bottom-message-text']}> {item.message}</text>
                    </div>
                  )
                }

              </div>
            ))
          }
        </div>
      </div>

    </PMGPopupContainer>
  );
};

export default observer(PMGJoinTeamApplyDialog);

