import { createContext, useContext, useEffect, useState } from 'react';
import axios from 'axios';
import { API_URL, slugify } from './Constant';
import axiosInstance from './axiosInstance';
import loader from "../assets/images/loading.gif"

// Buat context
const SlugContext = createContext();
const config = {
    headers: {
      Authorization: localStorage.getItem('token')
    }
};

export const SlugProvider = ({ children, logout }) => {
    const [sectionSlugMap, setSectionSlugMap] = useState({});
    const [topicSlugMap, setTopicSlugMap] = useState({});
    const [loading, setLoading] = useState(true);

    const fetchData = async () => {
      try {
          const sectionMapping = {};
          // const sectionResponse = await axios.get(`${API_URL}/section`, config);
          const sectionResponse = await axiosInstance.get(`/section`);
          sectionResponse.data.payload.forEach((section) => {
              const slug = slugify(section.NAME_SECTION);
              sectionMapping[slug] = section.ID_SECTION;
          });
          setSectionSlugMap(sectionMapping);
      } catch (error) {
        if (error.status === 403 || error.status === 401) {
          logout();
        }else{
          console.error('Error fetching section', error);
        }
      } finally{
          try{
              const topicMapping = {};
              // const topicResponse = await axios.get(`${API_URL}/topic`, config);
              const topicResponse = await axiosInstance.get(`/topic`);
              topicResponse.data.payload.forEach((topic) => {
                  const slug = slugify(topic.NAME_TOPIC);
                  topicMapping[slug] = topic.ID_TOPIC;
              });
              setTopicSlugMap(topicMapping);
          } catch (error) {
            if (error.status === 403 || error.status === 401) {
              logout();
            }else{
              console.error('Error fetching section', error);
              setLoading(false);
            }
          } finally{
              setLoading(false);
          }
      }
    };

  useEffect(() => {
      fetchData();
  }, [logout]);

  if (loading) {
    return (<div style={{backgroundColor:"#edf5ff"}} className='h-screen w-screen d-flex flex-column justify-content-center align-items-center'><img src={loader} alt="" /><h2 style={{color:"#4b84ca"}}>Loading...</h2></div>);
  }

  return (
    <SlugContext.Provider value={{ sectionSlugMap, topicSlugMap }}>
      {children}
    </SlugContext.Provider>
  );

};

export const useSlugContext = () => {
  return useContext(SlugContext);
};