import React, { useEffect, useState, useCallback } from "react";
import { SoluCXWidgetView } from "./SoluCXWidgetView";
import { _registerHost, _unregisterHost } from "./SoluCXWidget";
import type { WidgetConfig } from "./SoluCXWidget";
import { AsyncStorageService } from "./services/storage/AsyncStorageService";
import { buildStorageId } from "./services/storage/StorageIdBuilder";
import { WidgetStateManager } from "./services/WidgetStateManager";

export const SoluCXWidgetHost: React.FC = () => {
    const [config, setConfig] = useState<WidgetConfig | null>(null);
    const [refreshKey, setRefreshKey] = useState(0);

    const handleShow = useCallback((newConfig: WidgetConfig) => {
        setConfig(newConfig);
        setRefreshKey((k) => k + 1);
    }, []);

    const handleDismiss = useCallback(() => {
        if (config) {
            const storageId = buildStorageId(config.instanceKey, config.data);
            const storageService = new AsyncStorageService(storageId);
            const stateManager = new WidgetStateManager(storageService, storageId);

            void stateManager.updateTimestamp("lastDismiss")
            config.callbacks?.onClosed?.();
        }

        setConfig(null);
    }, [config]);

    useEffect(() => {
        _registerHost(handleShow, handleDismiss);
        return () => _unregisterHost();
    }, [handleShow, handleDismiss]);

    if (!config) return null;

    const wrappedCallbacks = {
        ...config.callbacks,
        onClosed: () => {
            config.callbacks?.onClosed?.();
            setConfig(null);
        },
    };

    return (
        <SoluCXWidgetView
            key={refreshKey}
            soluCXKey={config.instanceKey}
            type={config.type}
            data={config.data}
            options={config.options}
            callbacks={wrappedCallbacks}
        />
    );
};
