import { createContext, ReactNode, useContext, useEffect, useMemo, useState } from 'react';
import { AppBootstrapData } from '../types';
import { fetchBootstrapData } from '../services/api';

interface AppDataContextValue extends AppBootstrapData {
  loading: boolean;
  reload: () => Promise<void>;
}

const AppDataContext = createContext<AppDataContextValue | null>(null);

const emptyState: AppBootstrapData = {
  settings: {
    name: '',
    logoUrl: '',
    whatsapp: '',
    instagram: '',
    address: '',
    googleMapsLink: '',
    wazeLink: '',
    pixKey: '',
    serviceTax: 0,
    confirmationMessage: '',
    whatsappTemplate: '',
  },
  heroBanners: [],
  events: [],
  membershipPlans: [],
  leisureActivities: [],
  partners: [],
  sales: [],
  giftClaims: [],
  galleryImages: [],
};

export function AppDataProvider({ children }: { children: ReactNode }) {
  const [data, setData] = useState<AppBootstrapData>(emptyState);
  const [loading, setLoading] = useState(true);

  const load = async () => {
    setLoading(true);
    try {
      const nextData = await fetchBootstrapData();
      setData(nextData);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    void load();
  }, []);

  const value = useMemo(
    () => ({
      ...data,
      loading,
      reload: load,
    }),
    [data, loading],
  );

  return <AppDataContext.Provider value={value}>{children}</AppDataContext.Provider>;
}

export function useAppData() {
  const context = useContext(AppDataContext);

  if (!context) {
    throw new Error('useAppData deve ser usado dentro de AppDataProvider.');
  }

  return context;
}
