import React, {
  createContext,
  useContext,
  useState,
  useEffect,
  FC,
} from "react";

import { ASCore } from "../storageControl";

import { getStationList2 } from "../lib/getStationList";
import { injectJavascriptData } from "../lib/webViewInjectjavascript";

import { useNotification } from "../stateBox/useNotifications";
import { STORAGE_KEYS } from "@/constants/storage";

const initialState = {
  selectedLine: undefined,
  setSelectedLine: (e) => {},
  mapsStationData: undefined,
  setMapsStationData: (e) => {},
  iconSetting: undefined,
  setIconSetting: (e) => {},
  mapSwitch: undefined,
  setMapSwitch: (e) => {},
  stationMenu: undefined,
  setStationMenu: (e) => {},
  uiSetting: undefined,
  setUiSetting: (e) => {},
  LoadError: false,
  setLoadError: (e) => {},
  trainInfo: {
    trainNum: undefined,
    limited: undefined,
    trainData: undefined,
  },
  setTrainInfo: (e) => {},
  trainMenu: "true",
  setTrainMenu: (e) => {},
  updatePermission: false,
  setUpdatePermission: (e) => {},
  /** 各情報ソースの利用権限 */
  dataSourcePermission: { unyohub: false } as { unyohub: boolean },
  injectJavascript: "",
};

const TrainMenuContext = createContext(initialState);

export const useTrainMenu = () => {
  return useContext(TrainMenuContext);
};
type props = { children: React.ReactNode };
export const TrainMenuProvider: FC<props> = ({ children }) => {
  const { expoPushToken } = useNotification();
  const [selectedLine, setSelectedLine] = useState(undefined);
  const [mapsStationData, setMapsStationData] = useState(undefined);
  useEffect(() => {
    getStationList2().then(setMapsStationData);
  }, []);
  type boolType = "true" | "false" | undefined;
  //画面表示関連
  const [iconSetting, setIconSetting] = useState<boolType>(undefined);
  const [mapSwitch, setMapSwitch] = useState<boolType>(undefined);
  const [stationMenu, setStationMenu] = useState<boolType>(undefined);
  const [LoadError, setLoadError] = useState(false);

  //更新権限所有確認・情報ソース別利用権限（将来ロールが増えたらここに足す）
  const [updatePermission, setUpdatePermission] = useState(false);
  const [dataSourcePermission, setDataSourcePermission] = useState<{ unyohub: boolean }>({ unyohub: false });
  useEffect(() => {
    if (!expoPushToken) return;
    fetch(
      `https://jr-shikoku-backend-api-v1.haruk.in/check-permission?user_id=${expoPushToken}`
    )
      .then((res) => res.json())
      .then((res) => {
        const role: string = res.permission ?? "";
        setUpdatePermission(role === "administrator");
        setDataSourcePermission({
          unyohub: role === "administrator" || role === "unyoHubEditor",
        });
      })
      .catch(() => {});
  }, [expoPushToken]);

  //列車情報表示関連
  const [trainInfo, setTrainInfo] = useState({
    trainNum: undefined,
    limited: undefined,
    trainData: undefined,
  });

  //駅情報画面用
  const [trainMenu, setTrainMenu] = useState("true");

  //GUIデザインベース
  const [uiSetting, setUiSetting] = useState("tokyo");
  
  // 鉄道運用Hub使用設定
  const [useUnyohubSetting, setUseUnyohubSetting] = useState("false");

  // えれサイト使用設定
  const [useEleSiteSetting, setUseEleSiteSetting] = useState("false");

  //地図表示テキスト
  const injectJavascript = injectJavascriptData({
    mapSwitch,
    iconSetting,
    stationMenu,
    trainMenu,
    uiSetting,
    useUnyohub: useUnyohubSetting,
    useElesite: useEleSiteSetting,
  });

  useEffect(() => {
    //列車アイコンスイッチ
    ASCore({ k: STORAGE_KEYS.ICON_SWITCH, s: setIconSetting, d: "true", u: true });
    //地図スイッチ
    ASCore({ k: STORAGE_KEYS.MAP_SWITCH, s: setMapSwitch, d: "true", u: true });
    //駅メニュースイッチ
    ASCore({ k: STORAGE_KEYS.STATION_SWITCH, s: setStationMenu, d: "true", u: true });
    //列車メニュースイッチ
    ASCore({ k: STORAGE_KEYS.TRAIN_SWITCH, s: setTrainMenu, d: "true", u: true });
    //GUIデザインベーススイッチ
    ASCore({ k: STORAGE_KEYS.UI_SETTING, s: setUiSetting, d: "tokyo", u: true });
    //鉄道運用Hubスイッチ
    ASCore({ k: STORAGE_KEYS.USE_UNYOHUB, s: setUseUnyohubSetting, d: "false", u: true });
    //えれサイトスイッチ
    ASCore({ k: STORAGE_KEYS.USE_ELESITE, s: setUseEleSiteSetting, d: "false", u: true });
  }, []);

  return (
    <TrainMenuContext.Provider
      value={{
        selectedLine,
        setSelectedLine,
        mapsStationData,
        setMapsStationData,
        iconSetting,
        setIconSetting,
        mapSwitch,
        setMapSwitch,
        stationMenu,
        setStationMenu,
        uiSetting,
        setUiSetting,
        LoadError,
        setLoadError,
        trainInfo,
        setTrainInfo,
        trainMenu,
        setTrainMenu,
        updatePermission,
        setUpdatePermission,
        dataSourcePermission,
        injectJavascript,
      }}
    >
      {children}
    </TrainMenuContext.Provider>
  );
};
