import React, {
  createContext,
  useCallback,
  useContext,
  useEffect,
  useState,
} from 'react';
import privacyService, {
  CookieConsent,
  UpdateCookieConsentRequest,
} from '../../features/content/services/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?.has_decided);
        setHasDecided(decided);
      } catch (error: unknown) {
        // If API fails, check localStorage for previous decision
        const localFlag =
          typeof window !== 'undefined'
            ? window.localStorage.getItem('cookieConsentDecided')
            : null;
        
        if (localFlag === 'true') {
          // User has previously decided, don't show banner
          setHasDecided(true);
        } else {
          // No previous decision, show banner (consent will be null)
          setHasDecided(false);
        }
        
        if (import.meta.env.DEV) {
          const message = error instanceof Error ? error.message : String(error);
          console.error('Failed to load cookie consent:', message);
        }
      } finally {
        if (isMounted) {
          setIsLoading(false);
        }
      }
    };

    void loadConsent();

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

  const updateConsent = useCallback(
    async (payload: UpdateCookieConsentRequest) => {
      // SECURITY/COMPLIANCE: Update consent via backend API
      const updated = await privacyService.updateCookieConsent(payload);
      setConsent(updated);
      setHasDecided(true);
      // SECURITY: Store decision flag in localStorage (not sensitive data)
      // Actual consent preferences are stored securely on backend
      if (typeof window !== 'undefined') {
        window.localStorage.setItem('cookieConsentDecided', 'true');
      }
      // Trigger analytics reload to respect new consent
      window.dispatchEvent(new CustomEvent('cookie-consent-updated', { 
        detail: updated 
      }));
    },
    []
  );

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

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

// eslint-disable-next-line react-refresh/only-export-components
export const useCookieConsent = (): CookieConsentContextValue => {
  const ctx = useContext(CookieConsentContext);
  if (!ctx) {
    
    
    return {
      consent: null,
      isLoading: false,
      hasDecided: false,
      updateConsent: async () => {
        
        return;
      },
    };
  }
  return ctx;
};

