import CardsGrid from "@/components/Blocks/CardsGrid"
import DynamicContent from "@/components/Blocks/DynamicContent"
import ShortcutsList from "@/components/Blocks/ShortcutsList"
import JsonToHtml from "@/components/JsonToHtml"
import { getLang } from "@/i18n/serverContext"
import { modWebviewLink } from "@/utils/webviews"

import type { BlocksProps } from "@/types/components/blocks"
import { BlocksEnums } from "@/types/enums/blocks"

export default function Blocks({ blocks }: BlocksProps) {
  return blocks.map((block, idx) => {
    const firstItem = idx === 0
    switch (block.typename) {
      case BlocksEnums.block.CardsGrid:
        return (
          <CardsGrid
            key={`${block.cards_grid.title}-${idx}`}
            cards_grid={block.cards_grid}
          />
        )
      case BlocksEnums.block.Content:
        return (
          <section key={`${block.__typename}-${idx}`}>
            <JsonToHtml
              nodes={block.content.json.children}
              embeds={block.content.embedded_itemsConnection.edges}
            />
          </section>
        )
      case BlocksEnums.block.DynamicContent:
        const dynamicContent = {
          ...block.dynamic_content,
          link: block.dynamic_content.link
            ? {
                ...block.dynamic_content.link,
                href: modWebviewLink(
                  block.dynamic_content.link.href,
                  getLang()
                ),
              }
            : undefined,
        }

        return (
          <DynamicContent
            dynamic_content={dynamicContent}
            firstItem={firstItem}
            key={`${block.dynamic_content.title}-${idx}`}
          />
        )
      case BlocksEnums.block.Shortcuts:
        const shortcuts = block.shortcuts.shortcuts.map((shortcut) => ({
          ...shortcut,
          url: modWebviewLink(shortcut.url, getLang()),
        }))
        return (
          <ShortcutsList
            key={`${block.shortcuts.title}-${idx}`}
            firstItem={firstItem}
            shortcuts={shortcuts}
            subtitle={block.shortcuts.subtitle}
            title={block.shortcuts.title}
            hasTwoColumns={block.shortcuts.hasTwoColumns}
          />
        )
      default:
        return null
    }
  })
}
