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

const TEST_JSON_PATH = "/test.json";

const MyContext = createContext<MyContextProps | undefined>(undefined);

export const MyProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
  const [my_context, setMyContext] = useState<string>("initial value");

  const [test_first, setTestFirst] = useState<IFirst | undefined>(undefined);
  const [test_second, setTestSecond] = useState<ISecond | undefined>(undefined);
  const [test_third, setTestThird] = useState<IThird | undefined>(undefined);

  useEffect(() => {
    let test_third: IThird[] | [] = [];

    const fetchData = async () => {
      const res = await fetch(TEST_JSON_PATH);
      const res_json = await res.json();
      test_third = res_json;
      console.log({ test_third });
      console.log(test_third[0].content[0].content);
    };
    fetchData();
  }, []);

  return (
    <MyContext.Provider
      value={{
        my_context,
        setMyContext,
        //
        test_first,
        setTestFirst,
        test_second,
        setTestSecond,
        test_third,
        setTestThird,
      }}
    >
      {children}
    </MyContext.Provider>
  );
};

export const useMyContext = (): MyContextProps => {
  const context = useContext(MyContext);
  if (!context) {
    throw new Error("useMyContext must be used within a MyProvider");
  }
  return context;
};

interface MyContextProps {
  my_context: string;
  setMyContext: React.Dispatch<React.SetStateAction<string>>;
  //
  test_first: IFirst | undefined;
  setTestFirst: React.Dispatch<React.SetStateAction<IFirst | undefined>>;
  test_second: ISecond | undefined;
  setTestSecond: React.Dispatch<React.SetStateAction<ISecond | undefined>>;
  test_third: IThird | undefined;
  setTestThird: React.Dispatch<React.SetStateAction<IThird | undefined>>;
}

interface IFirst {
  test_s: string;
  test_i: number;
}

interface ISecond {
  test_s: string;
  test_i: number;
  content: IFirst[] | [];
}

interface IThird {
  test_s: string;
  test_i: number;
  content: ISecond[] | [];
}
