import React, {
  createContext,
  useCallback,
  useContext,
  useEffect,
  useState,
} from 'react';
import privacyService, {
  CookieConsent,
  UpdateCookieConsentRequest,
} from '../services/api/privacyService';

type CookieConsentContextValue = {
  consent: CookieConsent | null;
  isLoading: boolean;
  hasDecided: boolean;
  updateConsent: (payload: UpdateCookieConsentRequest) => Promise<void>;
};

const CookieConsentContext = createContext<CookieConsentContextValue | undefined>(
  undefined
);

export const CookieConsentProvider: React.FC<{ children: React.ReactNode }> = ({
  children,
}) => {
  const [consent, setConsent] = useState<CookieConsent | null>(null);
  const [isLoading, setIsLoading] = useState<boolean>(true);
  const [hasDecided, setHasDecided] = useState<boolean>(false);

  useEffect(() => {
    let isMounted = true;

    const loadConsent = async () => {
      try {
        const data = await privacyService.getCookieConsent();
        if (!isMounted) return;
        setConsent(data);

        
        const localFlag =
          typeof window !== 'undefined'
            ? window.localStorage.getItem('cookieConsentDecided')
            : null;
        const decided =
          (localFlag === 'true') || Boolean((data as any).has_decided);
        setHasDecided(decided);
      } catch (error) {
        if (import.meta.env.DEV) {
          
          console.error('Failed to load cookie consent', error);
        }
      } finally {
        if (isMounted) {
          setIsLoading(false);
        }
      }
    };

    void loadConsent();

    return () => {
      isMounted = false;
    };
  }, []);

  const updateConsent = useCallback(
    async (payload: UpdateCookieConsentRequest) => {
      const updated = await privacyService.updateCookieConsent(payload);
      setConsent(updated);
      setHasDecided(true);
      if (typeof window !== 'undefined') {
        window.localStorage.setItem('cookieConsentDecided', 'true');
      }
    },
    []
  );

  const value: CookieConsentContextValue = {
    consent,
    isLoading,
    hasDecided,
    updateConsent,
  };

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

export const useCookieConsent = (): CookieConsentContextValue => {
  const ctx = useContext(CookieConsentContext);
  if (!ctx) {
    
    
    return {
      consent: null,
      isLoading: false,
      hasDecided: false,
      updateConsent: async () => {
        
        return;
      },
    };
  }
  return ctx;
};

