'use client';

import usePreference from '@/hooks/helpers/usePreference';
import React, { useCallback, useEffect, useState } from 'react';
import { useParams } from 'next/navigation';
import { useGetAbout } from '@/app/[name]/(Main)/about/hooks/useAboutData';
import SplashScreen from '@/components/overlays/SplashScreen';
import { hexToOklch, calculateBrightness } from '@/lib/helpers/colorUtils';

function getSplashStorageKey(restaurantSlug: string) {
    return `splash-seen:${restaurantSlug}`;
}

function getSplashFingerprint(logo?: string | null, name?: string | null) {
    return `${logo ?? ''}|${name ?? ''}`;
}

type Props = {
    children: React.ReactNode
}

function applyPrimaryColor(colorHex: string) {
    const root = document.documentElement;
    const oklchColor = hexToOklch(colorHex);

    if (oklchColor) {
        root.style.setProperty('--primary', oklchColor);

        const brightness = calculateBrightness(colorHex);
        const foregroundOklch = brightness > 0.5 ? 'oklch(0 0 0)' : 'oklch(1 0 0)';
        root.style.setProperty('--primary-foreground', foregroundOklch);
    }
}

function PreferenceWrapper({ children }: Props) {
    const params = useParams();
    const restaurantSlug = typeof params.name === 'string' ? params.name : '';

    const { state: nightMode } = usePreference('night-mode', false);
    const { data: aboutData } = useGetAbout();

    const [showSplash, setShowSplash] = useState(false);
    const [mounted, setMounted] = useState(false);
    const [cachedLogo, setCachedLogo] = useState<string | null>(null);
    const [cachedName, setCachedName] = useState<string | null>(null);

    const handleSplashDismiss = useCallback(() => {
        setShowSplash(false);

        if (!restaurantSlug) return;

        const logo = aboutData?.data?.logo || cachedLogo;
        const name = aboutData?.data?.name || cachedName;
        const fingerprint = getSplashFingerprint(logo, name);
        localStorage.setItem(getSplashStorageKey(restaurantSlug), fingerprint);
    }, [aboutData?.data?.logo, aboutData?.data?.name, cachedLogo, cachedName, restaurantSlug]);

    useEffect(() => {
        setMounted(true);

        const savedColor = localStorage.getItem('theme-primary-color');
        if (savedColor) {
            applyPrimaryColor(savedColor);
        }

        const savedLogo = localStorage.getItem('restaurant-logo');
        const savedName = localStorage.getItem('restaurant-name');
        if (savedLogo) setCachedLogo(savedLogo);
        if (savedName) setCachedName(savedName);

        if (!restaurantSlug) return;

        const currentFingerprint = getSplashFingerprint(savedLogo, savedName);
        const seenFingerprint = localStorage.getItem(getSplashStorageKey(restaurantSlug));

        if (seenFingerprint !== currentFingerprint) {
            setShowSplash(true);
        }
    }, [restaurantSlug]);

    useEffect(() => {
        if (aboutData?.data?.menuColor) {
            localStorage.setItem('theme-primary-color', aboutData.data.menuColor);

            if (aboutData.data.logo) {
                localStorage.setItem('restaurant-logo', aboutData.data.logo);
            }
            if (aboutData.data.name) {
                localStorage.setItem('restaurant-name', aboutData.data.name);
            }

            applyPrimaryColor(aboutData.data.menuColor);
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [aboutData?.data?.menuColor]);

    useEffect(() => {
        if (!restaurantSlug || showSplash) return;

        const logo = aboutData?.data?.logo || cachedLogo;
        const name = aboutData?.data?.name || cachedName;
        const fingerprint = getSplashFingerprint(logo, name);
        const seenFingerprint = localStorage.getItem(getSplashStorageKey(restaurantSlug));

        if (seenFingerprint === '|' && fingerprint !== '|') {
            localStorage.setItem(getSplashStorageKey(restaurantSlug), fingerprint);
        }
    }, [aboutData?.data?.logo, aboutData?.data?.name, cachedLogo, cachedName, restaurantSlug, showSplash]);

    useEffect(() => {
        document.documentElement.setAttribute('data-theme', nightMode ? 'dark' : 'light');
    }, [nightMode]);

    const splashLogo = mounted
        ? (aboutData?.data?.logo || cachedLogo || undefined)
        : undefined;
    const splashName = mounted
        ? (aboutData?.data?.name || cachedName || undefined)
        : undefined;

    return (
        <>
            {children}
            {showSplash && (
                <SplashScreen
                    logo={splashLogo}
                    restaurantName={splashName}
                    onDismiss={handleSplashDismiss}
                />
            )}
        </>
    )
}

export default PreferenceWrapper
