import React, { createContext, useState, useContext, useEffect } from 'react';
import { api } from '../utils/api';
import { ArticleModel } from '../types/models';
import { ArticleContextModel } from '../types/contexts';
import { useAuth } from './Author';

const ArticleContext = createContext<ArticleContextModel | undefined>(undefined);

export const ArticleProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [articles, setArticles] = useState<ArticleModel[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);
  const { token } = useAuth();

  /** 🔹 Fetch articles (JWT automatically attached by api.ts interceptor) */
  const fetchArticles = async () => {
    try {
      setLoading(true);
      setError(null);

      const res = await api.get<ArticleModel[]>('/articles', { params: { skip: 0, limit: 100 } });
      const formatted = res.data.map((a) => ({ ...a, id: a._id || undefined }));
      setArticles(formatted);
    } catch (err: any) {
      console.error('Failed to fetch articles:', err);
      setError(err.response?.data?.detail || 'Failed to fetch articles');
    } finally {
      setLoading(false);
    }
  };

  /** 🔹 Auto-fetch articles whenever user logs in/out */
  useEffect(() => {
    // Always load once on mount
    // If endpoint requires JWT, fallback safely
    if (!token) {
      fetchArticles().catch(() => setLoading(false)); // try anyway (handles both public/protected)
    } else {
      fetchArticles();
    }
  }, [token]);

  return (
    <ArticleContext.Provider value={{ articles, loading, error, refreshArticles: fetchArticles }}>
      {children}
    </ArticleContext.Provider>
  );
};

export const useArticles = (): ArticleContextModel => {
  const ctx = useContext(ArticleContext);
  if (!ctx) throw new Error('useArticles must be used inside ArticleProvider');
  return ctx;
};
