import { useEffect, useMemo, useState } from 'preact/hooks';
import { registerModule, type AsukaModuleComponent } from '../../core/modules';
import { getAllImageProviders, isImageProviderAvailable, useImageProviderRegistryVersion } from '../../core/image-providers';
import { getI18n } from '../../core/i18n';
import { useT } from '../../hooks/useT';
import { useAsukaStore } from '../../store/asukaStore';
import { DEFAULT_PERMISSIONS } from '../../core/permissions';
import { registerCoreImageProviders } from '../../registerCoreImageProviders';
import { registerPremiumImageProviders } from '../../registerPremiumImageProviders';

import { Card, CardHeader, CardTitle, CardContent } from '../core/Card';
import { Tabs } from '../core/Tabs';

registerCoreImageProviders();
registerPremiumImageProviders();

const ImageModule: AsukaModuleComponent = ({ context }) => {
  const t = useT();
  const permissions = useAsukaStore((s: any) => s.permissions ?? DEFAULT_PERMISSIONS);
  const integrations = useAsukaStore((s: any) => s.integrations ?? {});
  const canUseLicenseFeature = useAsukaStore((s: any) => s.canUseLicenseFeature);
  const licenseResolutionTick = useAsukaStore((state: any) => state.licenseResolution?.resolvedAt ?? '');
  const providerRegistryVersion = useImageProviderRegistryVersion();
  const providers = useMemo(
    () => {
      void providerRegistryVersion;
      void licenseResolutionTick;
      return getAllImageProviders().filter((provider) =>
        isImageProviderAvailable(provider, {
          permissions,
          integrations,
          canUseLicenseFeature,
        }),
      );
    },
    [permissions, integrations, canUseLicenseFeature, providerRegistryVersion, licenseResolutionTick],
  );
  const [tab, setTab] = useState<string>('upload');

  const firstProvider = providers[0] ?? null;
  const activeTab = providers.some((item) => item.id === tab) ? tab : (firstProvider?.id ?? 'upload');
  const activeProvider = providers.find((item) => item.id === activeTab) ?? null;
  const ActivePanel = activeProvider?.render ?? null;

  useEffect(() => {
    if (!providers.some((item) => item.id === tab)) {
      setTab(firstProvider?.id ?? 'upload');
    }
  }, [providers, tab, firstProvider]);

  return (
    <Card>
      <CardHeader className="ask-flex ask-items-center ask-justify-between ask-gap-2">
        <CardTitle>{t('modules.image')}</CardTitle>
      </CardHeader>

      <CardContent className="ask-flex ask-flex-col ask-gap-4">
        <Tabs
          items={providers.map((provider) => ({
            id: provider.id,
            label: provider.label,
            icon: provider.icon,
          })) as any}
          value={activeTab as any}
          onChange={(id) => setTab(String(id))}
        />

        {ActivePanel ? (
          <ActivePanel context={context} />
        ) : (
          <div className="ask-rounded-xl ask-border ask-border-dashed ask-border-border ask-bg-surface2 ask-px-3 ask-py-3 ask-text-[12px] ask-text-textMuted">{t('common.noItems', 'No items.')}</div>
        )}
      </CardContent>
    </Card>
  );
};

registerModule({
  id: 'image',
  label: getI18n().t('modules.image'),
  icon: 'images',
  displayMode: 'floating',
  supportedEngines: ['fabric', '3d'],
  requiredCapabilities: ['addImage'],
  keepMounted: false,
  render: ImageModule,
});

export default ImageModule;
