"use client";

import { createContext, useContext, useEffect, useState } from "react";
import apiClient from "@/services/api.client";
import { API_ENDPOINTS } from "@/lib/constants/apiEndpoints";
import type {
  GeneralSettings,
  GeneralSettingItem,
} from "@/types/api/generalSettings.types";

interface GeneralSettingsContextValue {
  settings: GeneralSettings | null;
  isLoading: boolean;
}

const GeneralSettingsContext = createContext<GeneralSettingsContextValue>({
  settings: null,
  isLoading: true,
});

export function GeneralSettingsProvider({
  children,
}: {
  children: React.ReactNode;
}) {
  const [settings, setSettings] = useState<GeneralSettings | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    apiClient
      .post<{ result: GeneralSettingItem[] }>(API_ENDPOINTS.GENERAL_SETTING)
      .then(({ data }) => {
        const map = Object.fromEntries(
          (data.result ?? []).map((r) => [r.key, r.value]),
        );
        setSettings({
          appName: map.app_name ?? "DTNews",
          appLogo: map.app_logo ?? "",
          appIcon: map.app_icon ?? "",
          // API returns "currency" = "INR" (code) and "currency_code" = "₹" (symbol)
          currencyCode: map.currency ?? "INR",
          currencySymbol: map.currency_code ?? "₹",
          loginBgImg: map.login_bg_img ?? "",
          // API uses "email" and "contact" keys
          supportEmail: map.email ?? "",
          supportPhone: map.contact ?? "",
          copyrightText: map.copyright_text ?? "",
        });
      })
      .finally(() => setIsLoading(false));
  }, []);

  return (
    <GeneralSettingsContext.Provider value={{ settings, isLoading }}>
      {children}
    </GeneralSettingsContext.Provider>
  );
}

export const useGeneralSettings = () => useContext(GeneralSettingsContext);
