import { ChangeEvent, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { PATHS } from '@/shared/constants/paths';
import { useNavigate } from '@/shared/lib/hooks/use-navigate';
import { DEFAULT_PAGE_PARAM } from '@/entities/common/model/constant';
import { UserManageAuthList } from './user-manage-auth-list';
import { useUserFindMutation } from '@/entities/user/api/use-user-find-mutation';
import { UserListItem } from '@/entities/user/model/types';
import { useStore } from '@/shared/model/store';

export const UserManageWrap = () => {
  const { t } = useTranslation();
  const { navigate } = useNavigate();
  const midOptionsWithoutGids = useStore.getState().UserStore.selectOptionsMidsWithoutGids;
  const userMid = useStore.getState().UserStore.mid;
  let midItem = midOptionsWithoutGids.filter((value, index) => {
    return value.value === userMid;
  });
  
  const [mid, setMid] = useState<string>((midItem.length > 0)? userMid: '');
  const [userItems, setUserItems] = useState<Array<UserListItem>>([]);
  const [pageParam, setPageParam] = useState(DEFAULT_PAGE_PARAM);
  
  const { mutateAsync: userFind } = useUserFindMutation();

  const callList = () => {
    setPageParam(pageParam);
    userFind({ mid: mid, page: pageParam }).then((rs) => {
      console.log('API Response:', rs);
      console.log('Content:', rs.content);
      setUserItems(rs.content || []);
    });
  };

  const onClickToNavigation = () => {
    navigate(PATHS.account.user.addAccount, {
      state: {
        mid: mid,
      }
    });
  };

  useEffect(() => {
    if(!!mid){
      callList();
    }
  }, [mid]);
  
  return (
    <>
      {/* <div className="ing-list" style={{ display: 'flex', flexDirection: 'column', height: 'calc(100vh - 86px)' }}> */}
      <div className="ing-list pb-86">
        <div style={{ flexShrink: 0 }}>
          <div className="input-wrapper top-select mt-16">
            <select
              value={ mid }
              onChange={ (e: ChangeEvent<HTMLSelectElement>) => setMid(e.target.value)}
            >
            {
              midOptionsWithoutGids.map((value, index) => (
                <option
                  key={ value.value }
                  value={ value.value }
                >{ value.name }</option>
              ))
            }
            </select>
          </div>

          <div className="ing-title">{t('account.registrationStatus')}</div>
        </div>

        <div style={{ flex: 1, overflow: 'hidden', minHeight: 0 }}>
          { (!!userItems && userItems.length > 0) &&
            <UserManageAuthList
              userItems={ userItems }
              mid={ mid }
            ></UserManageAuthList>
          }
        </div>

        <div className="apply-row">
          <button
            className="btn-50 btn-blue flex-1"
            onClick={ () => onClickToNavigation() }
          >{t('account.addUser')}</button>
        </div>
      </div>
    </>
  );
};