import { h } from 'preact';
import { useEffect, useState } from 'preact/hooks';
import { registerImageProvider } from './core/image-providers';
import type { AsukaModuleComponent } from './core/modules';
import { getI18n } from './core/i18n';

type ProviderModule = Record<string, unknown> & { default?: AsukaModuleComponent };

type ProviderPanelLoader = () => Promise<ProviderModule>;

type ProviderPanelResolver = (mod: ProviderModule) => AsukaModuleComponent | undefined;

function createLazyProviderPanel(
  label: string,
  loader: ProviderPanelLoader,
  resolve: ProviderPanelResolver,
): AsukaModuleComponent {
  let cachedPanel: AsukaModuleComponent | null = null;
  let pendingLoad: Promise<AsukaModuleComponent> | null = null;

  const loadPanel = async (): Promise<AsukaModuleComponent> => {
    if (cachedPanel) return cachedPanel;
    if (!pendingLoad) {
      pendingLoad = loader().then((mod) => {
        const panel = resolve(mod);
        if (!panel) throw new Error(`[AsukaDesigner] ${label} provider panel could not be resolved.`);
        cachedPanel = panel;
        return panel;
      }).catch((error) => {
        pendingLoad = null;
        throw error;
      });
    }
    return pendingLoad;
  };

  const LazyProviderPanel: AsukaModuleComponent = (props) => {
    const [Panel, setPanel] = useState<AsukaModuleComponent | null>(() => cachedPanel);
    const [error, setError] = useState<string | null>(null);

    useEffect(() => {
      let mounted = true;
      loadPanel()
        .then((panel) => {
          if (!mounted) return;
          setPanel(() => panel);
          setError(null);
        })
        .catch((err) => {
          if (!mounted) return;
          setError(err instanceof Error ? err.message : String(err ?? 'Unknown error'));
        });
      return () => {
        mounted = false;
      };
    }, []);

    if (Panel) return h(Panel as any, props as any);

    const i18n = getI18n();
    return h(
      'div',
      {
        className: 'ask-rounded-xl ask-border ask-border-borderSubtle ask-bg-surfaceAlt ask-p-3 ask-text-[12px] ask-text-textMuted',
      },
      error
        ? `${i18n.t('common.error', 'Error')}: ${error}`
        : `${i18n.t('common.loading', 'Loading')} ${label}…`,
    );
  };

  return LazyProviderPanel;
}

const PixabayProviderPanel = createLazyProviderPanel(
  'Pixabay',
  () => import('./components/modules/PixabayImageModule'),
  (mod) => (mod.PixabayPanel as AsukaModuleComponent | undefined) ?? mod.default,
);

const PexelsProviderPanel = createLazyProviderPanel(
  'Pexels',
  () => import('./components/modules/PexelsImageModule'),
  (mod) => (mod.PexelsPanel as AsukaModuleComponent | undefined) ?? mod.default,
);

const FacebookProviderPanel = createLazyProviderPanel(
  'Facebook',
  () => import('./components/modules/FacebookImageModule'),
  (mod) => (mod.FacebookPanel as AsukaModuleComponent | undefined) ?? mod.default,
);

let registered = false;

export function registerPremiumImageProviders(
  registerProvider: typeof registerImageProvider = registerImageProvider,
): void {
  if (registered && registerProvider === registerImageProvider) return;
  if (registerProvider === registerImageProvider) registered = true;

  registerProvider({
    id: 'pixabay',
    label: 'Pixabay',
    icon: 'pixabay',
    group: 'premium',
    order: 30,
    integrationPath: 'pixabay.apiKey',
    hideWhenIntegrationMissing: true,
    permissionFlags: ['canUseExternalImageLibraries', 'canUsePixabayImages', 'canAddImage'],
    licenseFeature: 'pixabay',
    render: PixabayProviderPanel,
  });

  registerProvider({
    id: 'pexels',
    label: 'Pexels',
    icon: 'pexels',
    group: 'premium',
    order: 40,
    integrationPath: 'pexels.apiKey',
    hideWhenIntegrationMissing: true,
    permissionFlags: ['canUseExternalImageLibraries', 'canUsePexelsImages', 'canAddImage'],
    licenseFeature: 'pexels',
    render: PexelsProviderPanel,
  });

  registerProvider({
    id: 'facebook',
    label: 'Facebook',
    icon: 'facebook',
    group: 'premium',
    order: 50,
    integrationPath: 'facebook.appId',
    hideWhenIntegrationMissing: true,
    permissionFlags: ['canUseExternalImageLibraries', 'canUseFacebookImages', 'canAddImage'],
    licenseFeature: 'facebookImages',
    render: FacebookProviderPanel,
  });
}
