import { useCallback, useEffect, useState } from 'react';

export interface ColorTheme {
    primary: string;
    secondary?: string;
}

const setCookie = (name: string, value: string, days = 365) => {
    if (typeof document === 'undefined') {
        return;
    }

    const maxAge = days * 24 * 60 * 60;
    document.cookie = `${name}=${value};path=/;max-age=${maxAge};SameSite=Lax`;
};

const applyColors = (colors: ColorTheme) => {
    if (typeof document === 'undefined') {
        return;
    }

    let hasChanges = false;

    // Apply primary color only if it's different from current
    if (colors.primary) {
        const currentPrimary = document.documentElement.style.getPropertyValue('--color-primary');
        if (currentPrimary !== colors.primary) {
            document.documentElement.style.setProperty('--color-primary', colors.primary);
            document.documentElement.style.setProperty('--primary', colors.primary);
            document.documentElement.style.setProperty('--color-brand', colors.primary);
            document.documentElement.style.setProperty('--brand', colors.primary);
            hasChanges = true;
        }
    }

    // Apply secondary color only if it's different from current
    if (colors.secondary) {
        const currentSecondary = document.documentElement.style.getPropertyValue('--color-secondary');
        if (currentSecondary !== colors.secondary) {
            document.documentElement.style.setProperty('--color-secondary', colors.secondary);
            document.documentElement.style.setProperty('--secondary', colors.secondary);
            document.documentElement.style.setProperty('--color-brand-secondary', colors.secondary);
            document.documentElement.style.setProperty('--brand-secondary', colors.secondary);
            hasChanges = true;
        }
    }

    // Only log if there were actual changes
    if (hasChanges) {
    }
};

export function initializeColors() {
    const savedColors = localStorage.getItem('color-theme');
    if (savedColors) {
        try {
            const colors = JSON.parse(savedColors) as ColorTheme;
            applyColors(colors);
        } catch (error) {
            console.error('Failed to parse saved colors:', error);
        }
    }
}

export function useColors() {
    const [colorTheme, setColorTheme] = useState<ColorTheme | null>(null);
    const [isLoaded, setIsLoaded] = useState(false);

    const updateColors = useCallback((colors: ColorTheme) => {
        setColorTheme(colors);

        // Store in localStorage for client-side persistence
        localStorage.setItem('color-theme', JSON.stringify(colors));

        // Store in cookie for SSR
        setCookie('color-theme', JSON.stringify(colors));

        // Apply the colors immediately
        applyColors(colors);
    }, []);

    const updatePrimaryColor = useCallback(
        (color: string) => {
            const newColors: ColorTheme = {
                primary: color,
                secondary: colorTheme?.secondary,
            };
            updateColors(newColors);
        },
        [colorTheme, updateColors],
    );

    const updateSecondaryColor = useCallback(
        (color: string) => {
            const newColors: ColorTheme = {
                primary: colorTheme?.primary || '#000000',
                secondary: color,
            };
            updateColors(newColors);
        },
        [colorTheme, updateColors],
    );

    useEffect(() => {
        const savedColors = localStorage.getItem('color-theme');
        if (savedColors) {
            try {
                const colors = JSON.parse(savedColors) as ColorTheme;
                setColorTheme(colors);
                // Don't apply colors here since they should already be applied by initializeColors
            } catch (error) {
                console.error('Failed to parse saved colors:', error);
            }
        }
        setIsLoaded(true);
    }, []);

    return {
        colorTheme,
        isLoaded,
        updateColors,
        updatePrimaryColor,
        updateSecondaryColor,
    } as const;
}
