import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { getPatientTypes } from '@/states/patientTypeSlice';
import { getBodyParts } from '@/states/bodyPartSlice';
import { initializeProductState } from '@/states/productSlice';
import type { RootState, AppDispatch } from '@/states/store';

interface AppInitializerProps {
  onInitialized: () => void;
}

const AppInitializer: React.FC<AppInitializerProps> = ({ onInitialized }) => {
  const dispatch = useDispatch<AppDispatch>();
  const userInfo = useSelector((state: RootState) => state.userInfo);

  useEffect(() => {
    const fetchData = async () => {
      if (userInfo && userInfo.token) {
        await dispatch(getPatientTypes());
        await dispatch(
          getBodyParts({
            params: {},
          })
        );
        await dispatch(initializeProductState());
      }
      onInitialized();
    };
    fetchData();
  }, [dispatch, userInfo, onInitialized]);

  return <div>正在初始化，请稍候...</div>;
};

export default AppInitializer;
