import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { Achievement, Project } from '../data';
import { fetchAchievementsFromAPI, fetchProjectsFromAPI } from '../services/api';

interface DataContextType {
  achievements: Achievement[];
  projects: Project[];
  loading: boolean;
  error: string | null;
  refetch: () => Promise<void>;
}

const DataContext = createContext<DataContextType | undefined>(undefined);

export function DataProvider({ children }: { children: ReactNode }) {
  const [achievements, setAchievements] = useState<Achievement[]>([]);
  const [projects, setProjects] = useState<Project[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);

  const loadData = async () => {
    setLoading(true);
    setError(null);

    try {
      const results = await Promise.allSettled([
        fetchAchievementsFromAPI(),
        fetchProjectsFromAPI(),
      ]);

      const achievementsRes = results[0];
      const projectsRes = results[1];

      let hasError = false;
      let errorMsgs: string[] = [];

      if (achievementsRes.status === 'fulfilled') {
        setAchievements(achievementsRes.value);
      } else {
        console.error('Failed to fetch achievements:', achievementsRes.reason);
        errorMsgs.push('Gagal memuat data prestasi.');
        hasError = true;
      }

      if (projectsRes.status === 'fulfilled') {
        setProjects(projectsRes.value);
      } else {
        console.error('Failed to fetch projects:', projectsRes.reason);
        errorMsgs.push('Gagal memuat data portofolio.');
        hasError = true;
      }

      if (hasError) {
        setError(errorMsgs.join(' '));
      }
    } catch (err: any) {
      console.error('Unexpected error loading API data:', err);
      setError('Terjadi kesalahan yang tidak terduga saat memuat data.');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadData();
  }, []);

  return (
    <DataContext.Provider
      value={{
        achievements,
        projects,
        loading,
        error,
        refetch: loadData,
      }}
    >
      {children}
    </DataContext.Provider>
  );
}

export function useData() {
  const context = useContext(DataContext);
  if (context === undefined) {
    throw new Error('useData must be used within a DataProvider');
  }
  return context;
}
