import React, {
  createContext,
  useContext,
  useState,
  useEffect,
  useLayoutEffect,
  FC,
} from "react";
import { AS } from "@/storageControl";
import { useStationList } from "@/stateBox/useStationList";
import { StationProps } from "@/lib/CommonTypes";
const initialState = {
  favoriteStation: [],
  setFavoriteStation: () => {},
  lodAddMigration: () => {},
};

type initialStateType = {
  favoriteStation: any[];
  setFavoriteStation: (d: any) => void;
  lodAddMigration: () => void;
};
const FavoriteStationContext = createContext<initialStateType>(initialState);

export const useFavoriteStation = () => {
  return useContext(FavoriteStationContext);
};
type Props = {
  children: React.ReactNode;
};
export const FavoriteStationProvider: FC<Props> = ({ children }) => {
  const [favoriteStation, setFavoriteStation] = useState<StationProps[][]>([]);
  const { getStationDataFromName } = useStationList();
  const lodAddMigration = () => {
    const migration = favoriteStation.map((d) => {
      return getStationDataFromName(d[0].Station_JP);
    });
    setFavoriteStation(migration);
  };
  useEffect(() => {
    AS.getItem("favoriteStation")
      .then((d) => {
        const returnData: StationProps[][] = JSON.parse(d);
        setFavoriteStation(returnData);
      })
      .catch((error) => {
        // エラーログを記録（開発時のみ）
        if (__DEV__) {
          console.warn("お気に入り駅の読み込みに失敗しました:", error);
        }
      });
  }, []);
  return (
    <FavoriteStationContext.Provider
      value={{ favoriteStation, setFavoriteStation, lodAddMigration }}
    >
      {children}
    </FavoriteStationContext.Provider>
  );
};
