import { 
  Fragment,
  useCallback,
  useEffect,
  useState
} from 'react';
import { Outlet } from 'react-router-dom';
import { HeaderNavigation } from '@/widgets/navigation/header';
import { FooterNavigation } from '@/widgets/navigation/footer';
import { PullToRefresh } from '@/widgets/pull-to-refresh/pull-to-refresh';
import { useNavigate } from '@/shared/lib/hooks';
import { useScrollToTop } from '@/shared/lib/hooks/use-scroll-to-top';
import { HeaderType } from '@/entities/common/model/types';
import { useHomeGroupsMutation } from '@/entities/home/api/use-home-groups-mutation';
import { useUserInfo } from '@/entities/user/lib/use-user-info';
import { useAppBridge } from '@/hooks';
import { useStore } from '@/shared/model/store';
import { getLocalStorage, setLocalStorage } from '@/shared/lib';
import { StorageKeys } from '@/shared/constants/local-storage';
import { HomeGroupsParams, HomeGroupsResponse } from '@/entities/home/model/types';
import { BusinessPropertyByMidParams, BusinessPropertyByMidResponse, LoginResponse, ShortcutUserParams, ShortcutUserResponse } from '@/entities/user/model/types';
import { useCodesListByCodeClMutation } from '@/entities/common/api/use-codes-list-by-codeCl-mutaion';
import { useShortcutUserMutation } from '@/entities/user/api/use-shortcut-user-mutation';
import { useShortcutDefaultMutation } from '@/entities/user/api/use-shortcut-detault-mutation';
import { useBusinessPropertyByMidMutation } from '@/entities/user/api/use-business-property-by-mid-mutation';

export interface ContextType {
  setOnBack: (onBack: () => void) => void;
  setHeaderTitle: (title: string) => void;
  setIsPullToRefreshEnabled: (enabled: boolean) => void;
  setMenuOn: (menuOn: boolean) => void;
  setHeaderType: (headerType: HeaderType) => void;
  setFooterMode: (footerMode: boolean) => void;
  setFooterCurrentPage: (footerCurrentPage?: string | null) => void;
  setFavoriteEdit: (favoriteEdit?: boolean) => void;
};

export interface CallServiceCodeProps {
  codeCl: string;
  code1Filter?: Array<any>;
};

export const SubLayout = () => {
  useScrollToTop();
  const { 
    callLogin,
    updateUserData
  } = useUserInfo();

  const [onBack, setOnBack] = useState(undefined);
  const [headerTitle, setHeaderTitle] = useState<string>('');
  const [isPullToRefreshEnabled, setIsPullToRefreshEnabled] = useState<boolean>(false);
  const [menuOn, setMenuOn] = useState<boolean>(false);
  const [headerType, setHeaderType] = useState<HeaderType>(HeaderType.NoHeader);
  const [footerMode, setFooterMode] = useState<boolean>(false);
  const [footerCurrentPage, setFooterCurrentPage] = useState<undefined | string | null>(undefined);
  const [favoriteEdit, setFavoriteEdit] = useState<boolean>(false);
  const [headerNavigationKey, setHeaderNavigationKey] = useState<number>(1);
  const [loginSuccess, setLoginSuccess] = useState<boolean>(false);
  const [mid, setMid] = useState<string>();

  const { isNativeEnvironment } = useAppBridge();
  const { mutateAsync: homeGroups } = useHomeGroupsMutation();
  const { mutateAsync: codesListByCodeCl} = useCodesListByCodeClMutation();
  const { mutateAsync: shortcutUser } = useShortcutUserMutation();
  const { mutateAsync: shortcutDefault } = useShortcutDefaultMutation();
  const { mutateAsync: businessPropertyByMid } = useBusinessPropertyByMidMutation();

  const wrapperClassName = 'wrapper';
  
  const callHomeGroups = () => {
    let userInfo = useStore.getState().UserStore.userInfo;
    let params: HomeGroupsParams = {
      userid: userInfo.usrid
    };
    homeGroups(params).then((rs: HomeGroupsResponse) => {
      useStore.getState().UserStore.setUserMids(rs.mids);
      let options: Array<Record<string, string>> = rs.mids.map((value, index) => {
        return {
          name: value,
          value: value
        };
      });
      useStore.getState().UserStore.setSelectOptionsMids(options);
      
      if(!!rs.mids[0]){
        useStore.getState().UserStore.setMid(rs.mids[0]);
        setMid(rs.mids[0]);
      }
      setLoginSuccess(true);
      setHeaderNavigationKey(headerNavigationKey + 1);

      let filter0022: Array<string> = ['01', '02', '03', '05', '14', '21', '24', '26', '31'];
      callServiceCode({
        codeCl: '0022', 
        code1Filter: filter0022
      });
    });
  };

  const callBusinessPropertyByMid = () => {
    if(!!mid){
      let params: BusinessPropertyByMidParams = {
        mid: mid
      };
      businessPropertyByMid(params).then((rs: BusinessPropertyByMidResponse) => {
        console.log(rs);
      });
    }
    
  };

  const callSortcutDefault = () => {
    console.log("============================callSortcutDefault")
    let userInfo = useStore.getState().UserStore.userInfo;
    if(userInfo.usrid){
      let params: ShortcutUserParams = {
        usrid: userInfo.usrid
      };
      shortcutUser(params).then((rs: ShortcutUserResponse) => {
        // Modify iconFilePath to use menu_icon_{menuId}.svg format
        console.log("============================rs", rs)
        const modifiedShortcuts = rs.shortcuts.map(shortcut => ({
          ...shortcut,
          iconFilePath: `menu_icon_${shortcut.menuId}.svg`
        }));

        console.log("============================modifiedShortcuts", modifiedShortcuts)
        useStore.getState().UserStore.setUserFavorite(modifiedShortcuts);
      });
    }
  };

  const callShortcutUser = () => {
    console.log("============================callShortcutUser")
    let userInfo = useStore.getState().UserStore.userInfo;
    if(userInfo.usrid){
      let params: ShortcutUserParams = {
        usrid: userInfo.usrid
      };
      shortcutUser(params).then((rs: ShortcutUserResponse) => {
        console.log("============================rs", rs)
        if(!rs.usingDefault && rs.shortcuts){
          if(rs.shortcuts.length > 0){
            const modifiedShortcuts = rs.shortcuts.map(shortcut => ({
              ...shortcut,
              iconFilePath: `/images/menu_icon_${shortcut.menuId}.svg`
            }));

            console.log("============================modifiedShortcuts", modifiedShortcuts)
            useStore.getState().UserStore.setUserFavorite(modifiedShortcuts);
          }
          else{
            callSortcutDefault();
          }
        }
      });
    }
    
  };
    
  const handleLogin = useCallback(async () => {
    let userParmas;
    if(!isNativeEnvironment){
      userParmas = {
        id: 'nictest00',
        password: 'nictest00'
      };
    }
    callLogin(userParmas).then(() => {
      callHomeGroups();
      callShortcutUser();
    }).catch((error: any) => {
      setLoginSuccess(false);
    });
  }, []);

  const callServiceCode = ({
    codeCl, 
    code1Filter
  }: CallServiceCodeProps) => {
    let params = {
      codeCl: codeCl
    };
    let options = [];
    codesListByCodeCl(params).then((rs) => {
      options = rs.map((value, index) => {
        return {
          name: value.desc1,
          value: value.code1
        }
      });
      if(!!code1Filter){
        options = options.filter((value, index) => {
          return code1Filter.includes(value.value);
        });
      }
      options = options.sort((a, b) => a.value - b.value);
      options.unshift({
        name: '전체', value: ''
      });
      useStore.getState().CommonStore.setServiceCodes(options);
    });
  };

  const saveToken = (token: LoginResponse) => {
    updateUserData(token);
  };

  window.saveToken = saveToken;
  
  useEffect(() => {
    handleLogin();
  }, []);
  useEffect(() => {
    if(!!mid){
      // callBusinessPropertyByMid();
    }
  }, [mid]);

  return (
    <div className={ wrapperClassName }>
      <Fragment>
        <HeaderNavigation 
          onBack={ onBack } 
          headerTitle={ headerTitle } 
          menuOn={ menuOn }
          setMenuOn={ setMenuOn } 
          headerType={ headerType }
          favoriteEdit={ favoriteEdit }
          key={ headerNavigationKey }
          loginSuccess={ loginSuccess }
        />
        { loginSuccess && 
          <Outlet
            context={{
              setOnBack,
              setHeaderTitle,
              setIsPullToRefreshEnabled,
              setMenuOn,
              setHeaderType,
              setFooterMode,
              setFooterCurrentPage,
              setFavoriteEdit
            }}
          />
        }
        {
          footerMode && 
          <FooterNavigation
            setMenuOn={ setMenuOn }
            footerCurrentPage={ footerCurrentPage }
            setFavoriteEdit={ setFavoriteEdit }
          ></FooterNavigation>
        }
        
      </Fragment>
    </div>
  );
};
