import trainList from "@/assets/originData/trainList";
import useInterval from "@/lib/useInterval";
import { AS } from "@/storageControl";
import React, { createContext, FC, useContext, useEffect, useState } from "react";
const initialState = {
  allTrainDiagram: {},
  setAllTrainDiagram: (e) => {},
  allCustomTrainData: [],
  keyList: [],
};
type initialStateType = {
  allTrainDiagram: { [key: string]: string };
  setAllTrainDiagram: (e) => void;
  allCustomTrainData: any[];
  keyList: string[];
};

const AllTrainDiagramContext = createContext<initialStateType>(initialState);

export const useAllTrainDiagram = () => useContext(AllTrainDiagramContext);
type Props = {
  children: React.ReactNode;
};
export const AllTrainDiagramProvider:FC<Props> = ({ children }) => {
  const [allTrainDiagram, setAllTrainDiagram] = useState(trainList);
  const [allCustomTrainData, setAllCustomTrainData] = useState([]); // カスタム列車データ
  const [keyList, setKeyList] = useState<string[]>([]); // 第二要素
  useEffect(() => {
    if (allTrainDiagram && Object.keys(allTrainDiagram).length > 0)
      setKeyList(Object.keys(allTrainDiagram));
    else setKeyList([]);
  }, [allTrainDiagram]);
  const getTrainDiagram = () =>
    fetch("https://n8n.haruk.in/webhook/JR-shikoku-diagram-migrate-original")
      .then((res) => res.json())
      .then((res) => res.data)
      .then((res) => {
        const data = {};
        res.forEach((d) => {
          const keys = Object.keys(d)[0];
          data[keys] = d[keys];
        });
        //dataのkeyで並び替え
        const sortedData = Object.keys(data)
          .sort((a, b) => parseInt(a.replace(/[D,M]/, "")) - parseInt(b.replace(/[D,M]/, "")))
          .reduce((acc, key) => {
            acc[key] = data[key];
            return acc;
          }, {});
        return sortedData;
      })
      .then((res:any) => {
        setAllTrainDiagram(res);
        AS.setItem("allTrainDiagram", JSON.stringify(res));
      })
      .catch((d) => {
        AS.getItem("allTrainDiagram")
          .then((d) => setAllTrainDiagram(JSON.parse(d)))
          .catch(() => {
            alert("初回の路線情報の取得に失敗しました。");
          });
      });

  useEffect(() => {
    getTrainDiagram();
  }, []);
  useInterval(getTrainDiagram, 30000); //30秒毎に全在線列車取得

  const getCustomTrainData = () => {
    fetch("https://n8n.haruk.in/webhook/jr-shikoku-position-custom-datalist")
      .then((res) => res.json())
      .then((res) => {
        setAllCustomTrainData(res[0].data);
      })
      .catch(() => {
        alert("カスタム列車データの取得に失敗しました。");
      });
  };

  useEffect(() => {
    // カスタム列車データの取得
    getCustomTrainData();
  }, []);
  useInterval(getCustomTrainData, 30000); // 30秒毎にカスタム列車データ取得

  return (
    <AllTrainDiagramContext.Provider
      value={{
        allTrainDiagram,
        setAllTrainDiagram,
        allCustomTrainData,
        keyList,
      }}
    >
      {children}
    </AllTrainDiagramContext.Provider>
  );
};
