import React, {
    createContext,
    useContext,
    useState,
    useEffect,
    useCallback,
    useRef
} from 'react';
import type { ReactNode } from 'react';
import AsyncStorage from '@react-native-async-storage/async-storage';
import useHasFeature from '../hooks/auth/useHasFeature';
import useIsEmployee from '../hooks/auth/useIsEmployee';
import { MOBILE_CHRISTMAS_THEME } from '../constants/features';
import { logException } from '../services/sentry.service';

const CHRISTMAS_THEME_KEY = '@christmas_theme_enabled';
const SNOW_DURATION_MS = 10000;

const isWithinChristmasSeason = (): boolean => {
    const now = new Date();
    const month = now.getMonth();
    const day = now.getDate();
    return month === 11 || (month === 0 && day <= 7);
};

interface ChristmasThemeContextType {
    isAvailable: boolean;
    isEnabled: boolean;
    setEnabled: (enabled: boolean) => Promise<void>;
    loading: boolean;
    showSnow: boolean;
    onCatalogueScreenDisplayed: () => void;
}

const ChristmasThemeContext = createContext<
    ChristmasThemeContextType | undefined
>(undefined);

interface ChristmasThemeProviderProps {
    children: ReactNode;
}

export const ChristmasThemeProvider: React.FC<ChristmasThemeProviderProps> = ({
    children
}) => {
    const hasMobileChristmasTheme = useHasFeature(MOBILE_CHRISTMAS_THEME);
    const isEmployee = useIsEmployee();
    const [userPreference, setUserPreference] = useState<boolean>(false);
    const [loading, setLoading] = useState<boolean>(true);
    const [showSnow, setShowSnow] = useState<boolean>(true);
    const snowTimerRef = useRef<number | null>(null);

    const isWithinSeason = isWithinChristmasSeason();

    const isAvailable = hasMobileChristmasTheme && isWithinSeason && isEmployee;
    const isEnabled = isAvailable && userPreference;

    const loadPreference = async () => {
        try {
            const value = await AsyncStorage.getItem(CHRISTMAS_THEME_KEY);
            setUserPreference(value === null ? true : value === 'true');
        } catch (error) {
            logException(error, { context: 'ChristmasTheme.loadPreference' });
            setUserPreference(true);
        } finally {
            setLoading(false);
        }
    };

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

    useEffect(() => {
        return () => {
            if (snowTimerRef.current) {
                clearTimeout(snowTimerRef.current);
            }
        };
    }, []);

    const setEnabled = async (enabled: boolean) => {
        try {
            await AsyncStorage.setItem(CHRISTMAS_THEME_KEY, enabled.toString());
            setUserPreference(enabled);
            if (enabled) {
                setShowSnow(true);
            }
        } catch (error) {
            logException(error, {
                context: 'ChristmasTheme.setEnabled',
                enabled
            });
        }
    };

    const onCatalogueScreenDisplayed = useCallback(() => {
        if (isEnabled && showSnow) {
            if (snowTimerRef.current) {
                clearTimeout(snowTimerRef.current);
            }

            snowTimerRef.current = setTimeout(() => {
                setShowSnow(false);
            }, SNOW_DURATION_MS) as unknown as number;
        }
    }, [isEnabled, showSnow]);

    return (
        <ChristmasThemeContext.Provider
            value={{
                isAvailable,
                isEnabled,
                setEnabled,
                loading,
                showSnow,
                onCatalogueScreenDisplayed
            }}
        >
            {children}
        </ChristmasThemeContext.Provider>
    );
};

export const useChristmasTheme = (): ChristmasThemeContextType => {
    const context = useContext(ChristmasThemeContext);
    if (context === undefined) {
        // Log warning in development but don't crash the app
        // This is a non-critical festive feature - gracefully degrade instead
        if (__DEV__) {
            // eslint-disable-next-line no-console
            console.warn(
                'useChristmasTheme must be used within ChristmasThemeProvider. Returning safe defaults.'
            );
        }
        // Return safe defaults - Christmas theme just won't work
        return {
            isAvailable: false,
            isEnabled: false,
            setEnabled: async () => {},
            loading: false,
            showSnow: false,
            onCatalogueScreenDisplayed: () => {}
        };
    }
    return context;
};
