'use client';

import { useEffect, useRef, useMemo } from 'react';
import { useModelStore } from '@lib/store/modelStore';
import { useModels, useUserApiKeys, CONFIG_KEYS } from '@lib/hooks/useConfig';
import { useAuthStore } from '@/store/authStore';
import { useQueryClient } from '@tanstack/react-query';
import { logger } from '@/lib/utils/logger';

const log = logger.namespace('ModelInitializer');

export function ModelInitializer() {
    const setModels = useModelStore((state) => state.setModels);
    const isAuthenticated = useAuthStore((s) => s.isAuthenticated);
    const hydrate = useAuthStore((s) => s.hydrate);
    const queryClient = useQueryClient();

    // Hydrate auth state on mount
    useEffect(() => {
        hydrate();
    }, [hydrate]);
    // useModels auto-fetches on mount (enabled: true by default). No manual refetch needed.
    const { data, isLoading, error } = useModels();
    const { data: apiKeys } = useUserApiKeys(isAuthenticated);

    // Get configured providers
    const configuredProviders = useMemo(() => {
        return new Set(apiKeys?.filter(k => k.isActive).map(k => k.provider) || []);
    }, [apiKeys]);

    // Filter models based on configured API keys
    const filteredData = useMemo(() => {
        if (!data) return null;

        const result: {
            image: Record<string, any>;
            video: Record<string, any>;
            audio: Record<string, any>;
            lyrics: Record<string, any>;
            music: Record<string, any>;
            llm: Record<string, any>;
        } = {
            image: {},
            video: {},
            audio: {},
            lyrics: {},
            music: {},
            llm: {}
        };

        for (const [type, typeModels] of Object.entries(data)) {
            if (type in result && typeof typeModels === 'object' && typeModels !== null) {
                for (const [id, model] of Object.entries(typeModels)) {
                    const modelProvider = (model as any)?.provider;
                    if (modelProvider && configuredProviders.has(modelProvider)) {
                        (result as any)[type][id] = model;
                    }
                }
            }
        }
        return result;
    }, [data, configuredProviders]);

    // Refetch models when authentication state changes to true
    const prevAuthRef = useRef(isAuthenticated);
    useEffect(() => {
        // Only refetch when auth state transitions from false→true (not on initial mount)
        if (isAuthenticated && !prevAuthRef.current) {
            log.log('User authenticated, refreshing models...');
            queryClient.invalidateQueries({ queryKey: CONFIG_KEYS.models() });
        }
        prevAuthRef.current = isAuthenticated;
    }, [isAuthenticated, queryClient]);

    // Sync React Query data → zustand store (runs only when `filteredData` reference changes)
    const prevDataRef = useRef(filteredData);
    useEffect(() => {
        if (!filteredData || filteredData === prevDataRef.current) return;
        prevDataRef.current = filteredData;

        if (filteredData.image || filteredData.video || filteredData.llm) {
            setModels(filteredData);

            const imageCount = Object.keys(filteredData.image || {}).length;
            const videoCount = Object.keys(filteredData.video || {}).length;
            const llmCount = Object.keys(filteredData.llm || {}).length;
            const audioCount = Object.keys(filteredData.audio || {}).length;
            const lyricsCount = Object.keys(filteredData.lyrics || {}).length;
            const musicCount = Object.keys(filteredData.music || {}).length;

            log.log('Models loaded (filtered by API keys):', {
                total: imageCount + videoCount + llmCount + audioCount + lyricsCount + musicCount,
                image: imageCount, video: videoCount, llm: llmCount,
                audio: audioCount, lyrics: lyricsCount, music: musicCount,
            });
        }
    }, [filteredData, setModels]);

    useEffect(() => {
        if (error) {
            log.error('Failed to load models:', error);
        }
    }, [error]);

    return null;
}
