'use client';

import {
  createContext,
  useCallback,
  useContext,
  useEffect,
  useMemo,
  useState,
  type ReactNode,
} from 'react';
import { api, apiPaths } from '@/lib/api';

/** يطابق `GET /general/footer` */
export type SiteFooterData = {
  tax_rate_percent?: number;
  logo_url: string | null;
  favicon_url?: string | null;
  site_name_ar: string;
  site_name_en: string;
  brand_name_ar?: string;
  brand_name_en?: string;
  description_ar: string;
  description_en: string;
  email: string;
  phone: string;
};

export type FooterSocial = { id?: number; key: string; url: string; icon: string };

type GeneralSocialRow = { link: string; name: string; icon: string };

type SiteFooterContextValue = {
  footer: SiteFooterData | null;
  socials: FooterSocial[];
  loading: boolean;
  loadError: boolean;
  refetch: () => void;
};

const SiteFooterContext = createContext<SiteFooterContextValue | null>(null);

export function SiteFooterProvider({ children }: { children: ReactNode }) {
  const [footer, setFooter] = useState<SiteFooterData | null>(null);
  const [socials, setSocials] = useState<FooterSocial[]>([]);
  const [loading, setLoading] = useState(true);
  const [loadError, setLoadError] = useState(false);

  const load = useCallback(() => {
    setLoadError(false);
    setLoading(true);
    Promise.allSettled([
      api.get<SiteFooterData>(apiPaths.general.footer),
      api.get<GeneralSocialRow[]>(apiPaths.general.socials),
    ])
      .then((results) => {
        const footerResult = results[0];
        const socialsResult = results[1];

        if (footerResult.status === 'fulfilled') {
          const footerRes = footerResult.value;
          if (footerRes.key === 'success' && footerRes.data) {
            setFooter(footerRes.data as SiteFooterData);
          } else {
            setLoadError(true);
            setFooter(null);
          }
        } else {
          setLoadError(true);
          setFooter(null);
        }

        if (socialsResult.status === 'fulfilled') {
          const socialsRes = socialsResult.value;
          if (socialsRes.key === 'success' && socialsRes.data && Array.isArray(socialsRes.data)) {
            const mapped = (socialsRes.data as GeneralSocialRow[]).map((s, index) => ({
              id: index,
              key: (s.name || `social-${index}`).trim(),
              url: (s.link || '').trim(),
              icon: (s.icon || 'ri-link').trim(),
            }));
            setSocials(mapped);
          } else {
            setSocials([]);
          }
        } else {
          setSocials([]);
        }
      })
      .finally(() => setLoading(false));
  }, []);

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

  const value = useMemo(
    () => ({
      footer,
      socials,
      loading,
      loadError,
      refetch: load,
    }),
    [footer, socials, loading, loadError, load]
  );

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

export function useSiteFooter(): SiteFooterContextValue {
  const ctx = useContext(SiteFooterContext);
  if (!ctx) {
    throw new Error('useSiteFooter must be used within SiteFooterProvider');
  }
  return ctx;
}

/** شعار الموقع للهيدر/الفوتر — من `logo` في إعدادات التطبيق (ليس intro_logo) */
export function useSiteLogoUrl(): string | null {
  const { footer } = useSiteFooter();
  const url = (footer?.logo_url ?? '').trim();
  return url !== '' ? url : null;
}
