import React, { createContext, useContext } from 'react';
import { useQuery } from '@tanstack/react-query';
import api from '../utils/api';

type subTopic = {
  id: Number;
  subtopic: string;
}

type Topic = {
  name: string;
  subtopics: subTopic[];
};

type TopicsContextType = {
  topics: Topic[] | undefined;
  isLoading: boolean;
  isError: boolean;
};

const TopicsContext = createContext<TopicsContextType | undefined>(undefined);

type TopicsResponse = {
  [category: string]: subTopic[];
};

const transformTopics = (data: TopicsResponse): Topic[] => {
  return Object.entries(data).map(([name, subtopics]) => ({
    name,
    subtopics, // already has id and subtopic from the response
  }));
};

export const TopicsProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const { data: topics, isLoading, isError } = useQuery({
    queryKey: ['topics'],
    queryFn: () => api.get<TopicsResponse>('/articles/topics').then(res => transformTopics(res.data)),
    staleTime: 90 * 60 * 1000, // 90 minutes in cache
  });

  return (
    <TopicsContext.Provider value={{ topics, isLoading, isError }}>
      {children}
    </TopicsContext.Provider>
  );
};

export const useTopics = (): TopicsContextType => {
  const context = useContext(TopicsContext);
  if (!context) throw new Error('useTopics must be used within a TopicsProvider');
  return context;
};
