import { getCreationList } from '@/services/creations';
import { getCreatorList } from '@/services/creators';
import type { HomepageCollectionTextFields } from '@/services/homeCollections';

import { toNonEmptyString } from '@/utils/stringNormalization';

import type { CreationListItem } from '@/types/Creation';
import type { CreatorListData } from '@/types/Creator';

import HomepageMapShowcaseClient from './HomepageMapShowcaseClient';
import {
  HOMEPAGE_MAP_CONTENT_TYPES,
  HOMEPAGE_MAP_CREATOR_META_IDS,
  HOMEPAGE_MAP_EXCLUDED_CREATION_IDS,
  type HomepageMapCreatorOption,
} from './homepageMapShowcaseConfig';

const toCreationArray = (response: unknown): CreationListItem[] => {
  if (Array.isArray(response)) return response as CreationListItem[];

  if (
    response &&
    typeof response === 'object' &&
    'list' in response &&
    Array.isArray((response as { list?: unknown }).list)
  ) {
    return (response as { list: CreationListItem[] }).list;
  }

  return [];
};

const toCreatorOption = (creator: CreatorListData): HomepageMapCreatorOption | null => {
  const id = toNonEmptyString(creator.alkotoAzonosito);
  const name = toNonEmptyString(creator.nev);
  if (!id || !name) return null;

  return {
    id,
    name,
    profession: toNonEmptyString(creator.szakma),
    avatarKey: toNonEmptyString(creator.profilkep?.key),
  };
};

const loadCreatorOptions = async (): Promise<HomepageMapCreatorOption[]> => {
  try {
    const creators = await getCreatorList({
      body: {
        metaIdList: [...HOMEPAGE_MAP_CREATOR_META_IDS],
        withCoord: true,
      },
    });

    const byId = new Map<string, HomepageMapCreatorOption>();
    for (const creator of creators) {
      const option = toCreatorOption(creator);
      if (!option) continue;
      if (byId.has(option.id)) continue;
      byId.set(option.id, option);
    }

    return Array.from(byId.values()).sort((left, right) =>
      left.name.localeCompare(right.name, 'hu')
    );
  } catch (error) {
    console.error('Homepage map showcase creator list fetch error:', error);
    return [];
  }
};

const loadInitialCreations = async (): Promise<CreationListItem[]> => {
  try {
    const response = await getCreationList({
      maxResults: 5000,
      contentType: [...HOMEPAGE_MAP_CONTENT_TYPES],
      withCoord: true,
      imageNeeded: true,
    });

    return toCreationArray(response).filter(
      (creation) => !HOMEPAGE_MAP_EXCLUDED_CREATION_IDS.has(creation.alkotasAzonosito)
    );
  } catch (error) {
    console.error('Homepage map showcase initial creations fetch error:', error);
    return [];
  }
};

interface HomepageMapShowcaseProps {
  textFields?: HomepageCollectionTextFields | null;
}

const HomepageMapShowcase = async ({ textFields }: HomepageMapShowcaseProps) => {
  try {
    const [initialCreations, creatorOptions] = await Promise.all([
      loadInitialCreations(),
      loadCreatorOptions(),
    ]);

    return (
      <HomepageMapShowcaseClient
        initialCreations={initialCreations}
        creatorOptions={creatorOptions}
        textFields={textFields}
      />
    );
  } catch (error) {
    console.error('Homepage map showcase error:', error);
    return null;
  }
};

export default HomepageMapShowcase;
