import type { ComponentType } from 'react';
import { useState, useCallback } from 'react';
import { Loader2 } from 'lucide-react';
import { useClient } from 'hooks/useClient';

type UserAppPanelProps = { panelId: string };

export const createUserAppPanel = (slug: string): ComponentType<UserAppPanelProps> => {
  const UserAppPanel = ({ panelId }: UserAppPanelProps) => {
    const client = useClient();
    const [iframeKey, setIframeKey] = useState(0);
    const [loading, setLoading] = useState(true);

    const token = client.token;
    const src = token
      ? `/api/app-serve/${slug}/?token=${encodeURIComponent(token)}`
      : `/api/app-serve/${slug}/`;

    const handleLoad = useCallback(() => setLoading(false), []);

    return (
      <div className="relative h-full w-full">
        {loading && (
          <div className="absolute inset-0 flex items-center justify-center text-duck-dark/50">
            <Loader2 className="h-5 w-5 animate-spin" />
          </div>
        )}
        <iframe
          key={iframeKey}
          src={src}
          className="h-full w-full border-none"
          title={slug}
          onLoad={handleLoad}
        />
      </div>
    );
  };

  UserAppPanel.displayName = `UserAppPanel(${slug})`;
  return UserAppPanel;
};
