import React, { createContext, useContext, useState, useEffect } from 'react'
import { getUser, getColorTestFor } from '../utils/storage'
import ColorBlindnessFilters from '../components/ColorBlindnessFilters'

const ColorBlindnessContext = createContext()

export const useColorBlindness = () => useContext(ColorBlindnessContext)

export function ColorBlindnessProvider({ children }) {
    const [isEnabled, setIsEnabled] = useState(false)
    const [type, setType] = useState('none') // protanopia, deuteranopia, tritanopia, achromatopsia
    const [loaded, setLoaded] = useState(false)

    // Load initial state from backend
    useEffect(() => {
        const loadSettings = () => {
            const user = getUser()
            console.log('CB Context: Loading settings for user', user?.id)
            if (user?.id) {
                fetch(`http://localhost/landingpage1/lomba/color_blindness.php?user_id=${user.id}&_t=${Date.now()}`)
                    .then(res => res.json())
                    .then(data => {
                        console.log('CB Context: Fetched data', data)
                        if (data.type) setType(data.type)
                        if (typeof data.enabled === 'boolean') setIsEnabled(data.enabled)
                        setLoaded(true)
                    })
                    .catch(err => {
                        console.error('Failed to load CB settings', err)
                        setLoaded(true)
                    })
            } else {
                console.log('CB Context: No user, resetting')
                setType('none')
                setIsEnabled(false)
                setLoaded(true)
            }
        }

        loadSettings()
        window.addEventListener('kk_user_changed', loadSettings)
        return () => window.removeEventListener('kk_user_changed', loadSettings)
    }, [])

    // Sync changes to backend automatically when state changes
    // Sync changes to backend automatically when state changes
    useEffect(() => {
        const u = getUser()
        if (loaded && u?.id) {
            // Debounce slightly or just save. Since it's user interaction, immediate is fine but let's ensure we have valid data.
            if (type) {
                saveSettings(type, isEnabled)
            }
        }
    }, [type, isEnabled, loaded])

    const saveSettings = async (newType, newEnabled) => {
        const u = getUser()
        if (!u?.id) return
        try {
            await fetch('http://localhost/landingpage1/lomba/color_blindness.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    user_id: u.id,
                    type: newType,
                    enabled: newEnabled
                })
            })
        } catch (e) { console.error('Failed to save CB settings', e) }
    }

    // Apply filter to body
    useEffect(() => {
        if (isEnabled && type !== 'none') {
            document.body.style.filter = `url(#${type})`
            document.body.style.webkitFilter = `url(#${type})`
        } else {
            document.body.style.filter = 'none'
            document.body.style.webkitFilter = 'none'
        }
        return () => {
            document.body.style.filter = 'none'
            document.body.style.webkitFilter = 'none'
        }
    }, [isEnabled, type])

    const updateFromTest = (classification) => {
        const cls = classification.toLowerCase()
        console.log('UpdateFromTest called with:', classification, 'Normalized:', cls)
        let newType = 'none'

        if (cls.includes('protanopia')) newType = 'protanopia'
        else if (cls.includes('protanomaly')) newType = 'protanomaly'
        else if (cls.includes('deuteranopia')) newType = 'deuteranopia'
        else if (cls.includes('deuteranomaly')) newType = 'deuteranomaly'
        else if (cls.includes('tritanopia')) newType = 'tritanopia'
        else if (cls.includes('tritanomaly')) newType = 'tritanomaly'
        else if (cls.includes('monochromacy') || cls.includes('achromatopsia')) newType = 'achromatopsia'

        console.log('Setting new CB type:', newType)
        setType(newType)
        const shouldEnable = newType !== 'none'
        setIsEnabled(shouldEnable)
        // No manual save needed, useEffect will handle it
    }

    return (
        <ColorBlindnessContext.Provider value={{ isEnabled, setIsEnabled, type, setType, updateFromTest }}>
            <ColorBlindnessFilters />
            {children}
        </ColorBlindnessContext.Provider>
    )
}
