import React from 'react';
import { getUnisphereInstance } from '@unisphere/runtime-js'
import { useEffect, useRef } from 'react'
import { useState } from 'react';
import { PlaygroundCard } from '@site/src/components/ui-shared/playground-card';

export const HelloWorldExperience = ({ preload }: { preload?: boolean }) => {

    const [loaded, setLoaded] = useState(false);
    const unmountRef = useRef<(() => void) | null>(null);

    const loadHelloWorldExperience = async () => {
        try {
            setLoaded(true);
            const workspace = await getUnisphereInstance('')
            const { runtime, runtimeInfo } = await workspace.loadRuntime('unisphere.widget.hello', 'hello-world', {});

            if (runtime) {
                const { unsubscribe } = runtime.mountVisual({
                    type: 'docs',
                    target: 'hello-world-experience-container',
                    settings: {}
                });

                // Store unmount function for cleanup
                unmountRef.current = unsubscribe;

                console.log('✅ Hello World loaded:', runtimeInfo);
            }
        } catch (e) {
            console.error('Failed to load Hello World experience:', e)
        }
    }

    useEffect(() => {
        if (preload) {
            loadHelloWorldExperience();
        }

        // Cleanup on unmount
        return () => {
            if (unmountRef.current) {
                unmountRef.current();
                unmountRef.current = null;
            }
        };
    }, [preload])

    const playIcon = (
        <svg
            width="32"
            height="32"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="1.5"
            style={{
                color: 'var(--ifm-color-content-secondary)',
                opacity: 0.7
            }}
        >
            <circle cx="12" cy="12" r="10" />
            <polygon points="10,8 16,12 10,16 10,8" />
        </svg>
    );

    return (
        <PlaygroundCard
            title="Playground - Hello World Experience"
            icon={!loaded ? playIcon : undefined}
        >
            <div style={{ marginBottom: '1rem' }}>
                {loaded ? (
                    <div style={{ color: 'var(--ifm-color-content-secondary)', fontSize: '0.9rem', marginBottom: '0.5rem' }}>
                        This hello-world experience is {preload ? 'preloaded' : 'dynamically loaded at runtime'} to verify your Unisphere integration.
                        <br />
                        <strong style={{ color: 'var(--ifm-color-content)' }}>The widget should appear below!</strong>
                    </div>
                ) : (
                    <div style={{ color: 'var(--ifm-color-content-secondary)', fontSize: '0.9rem' }}>
                        Click the button below to load the hello-world experience and verify your workspace integration
                    </div>
                )}
            </div>

            <div
                style={{
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    gap: '12px',
                    padding: '12px 24px',

                    minHeight: '48px',
                }}
            >
                <div id="hello-world-experience-container"></div>
                {!loaded && (
                    <button
                        onClick={loadHelloWorldExperience}
                        style={{
                            padding: '8px 16px',
                            background: 'var(--ifm-color-primary)',
                            color: 'white',
                            border: 'none',
                            borderRadius: 'var(--ifm-code-border-radius)',
                            fontSize: '14px',
                            fontWeight: '500',
                            cursor: 'pointer',
                            transition: 'all 0.2s ease',
                            boxShadow: 'var(--ifm-global-shadow-lw)',
                        }}
                        onMouseEnter={(e) => {
                            e.currentTarget.style.backgroundColor = 'var(--ifm-color-primary-dark)';
                            e.currentTarget.style.transform = 'translateY(-1px)';
                            e.currentTarget.style.boxShadow = 'var(--ifm-global-shadow-md)';
                        }}
                        onMouseLeave={(e) => {
                            e.currentTarget.style.backgroundColor = 'var(--ifm-color-primary)';
                            e.currentTarget.style.transform = 'translateY(0)';
                            e.currentTarget.style.boxShadow = 'var(--ifm-global-shadow-lw)';
                        }}
                    >
                        Load Hello World Experience
                    </button>
                )}
            </div>
        </PlaygroundCard>
    );
}
