"use client";
import { createContext, useContext, useEffect, useMemo, useState } from "react";
import apiClient from "./axiosClient";
import { API_ENDPOINTS } from "./apiEndpoints";
import { GeneralSettings, AppPage } from "@/types/common";

const GeneralSettingsContext = createContext<{
  settings: GeneralSettings | null;
  pages: AppPage[];
  isLoading: boolean;
}>({ settings: null, pages: [], isLoading: true });

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

  useEffect(() => {
    Promise.all([
      apiClient.post(API_ENDPOINTS.GENERAL_SETTING),
      apiClient
        .post(API_ENDPOINTS.GET_PAGES)
        .catch(() => ({ data: { result: [] } })),
    ])
      .then(([{ data: settingsData }, { data: pagesData }]) => {
        const map = Object.fromEntries(
          (settingsData.result ?? []).map(
            (r: { key: string; value: string }) => [r.key, r.value],
          ),
        );
        setSettings({
          appName: map.app_name ?? "Doliplay",
          appVersion: map.app_version ?? "",
          appLogo: map.app_logo ?? "",
          appIcon: map.app_icon ?? "",
          appDescription: map.app_description ?? "",
          author: map.author ?? "",
          website: map.website ?? "",
          // API stores code in 'currency' and symbol in 'currency_code'
          currencyCode: map.currency ?? "USD",
          currencySymbol: map.currency_code ?? "$",
          // Login page assets
          loginBgImg: map.panel_login_page_bg_image ?? "",
          loginBgColor: map.panel_login_page_bg_color ?? "#000000",
          // Contact — actual API keys are 'email' and 'contact'
          supportEmail: map.email ?? "",
          supportPhone: map.contact ?? "",
          copyrightText: map.copyright_text ?? "",
          pageBackgroundColor: map.page_background_color ?? "",
          pageTitleColor: map.page_title_color ?? "",
          companyName: map.company_name ?? "",
          companyLogo: map.company_logo ?? "",
          oneSignalAppId: map.onesignal_app_id ?? "",
          oneSignalRestKey: map.onesignal_rest_key ?? "",
          vapIdKey: map.vap_id_key ?? "",
          minWithdrawalAmount: parseFloat(map.min_withdrawal_amount ?? "0") || 0,
          streamApiKey: map.stream_api_key ?? "",
          isLiveStreamingFake: map.is_live_streaming_fake === "1",
        });

        setPages(
          (pagesData.result ?? []).map(
            (p: { title: string; url: string; icon: string }) => ({
              title: p.title,
              url: p.url,
              icon: p.icon,
            }),
          ),
        );
      })
      .finally(() => setIsLoading(false));
  }, []);

  const value = useMemo(
    () => ({ settings, pages, isLoading }),
    [settings, pages, isLoading],
  );

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

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