import type { CollectionAfterReadHook } from 'payload'
import type { DefaultTypedEditorState } from '@payloadcms/richtext-lexical'

import type { Page } from '@/payload-types'

const textToLexical = (value: string): DefaultTypedEditorState => {
  const lines = value
    .split(/\r?\n/)
    .map((line) => line.trim())
    .filter(Boolean)

  const children =
    lines.length > 0
      ? lines.map((line) => ({
          type: 'paragraph' as const,
          children: [
            {
              type: 'text' as const,
              detail: 0,
              format: 0,
              mode: 'normal' as const,
              style: '',
              text: line,
              version: 1,
            },
          ],
          direction: 'ltr' as const,
          format: '',
          indent: 0,
          version: 1,
        }))
      : [
          {
            type: 'paragraph' as const,
            children: [],
            direction: 'ltr' as const,
            format: '',
            indent: 0,
            version: 1,
          },
        ]

  return {
    root: {
      type: 'root',
      children,
      direction: 'ltr',
      format: '',
      indent: 0,
      version: 1,
    },
  }
}

const normalizeRichTextValue = (value: unknown) => {
  if (typeof value === 'string') {
    return textToLexical(value)
  }

  return value
}

const normalizeLayout = (layout: Page['layout']) => {
  if (!Array.isArray(layout)) return layout

  return layout.map((block) => {
    if (!block || typeof block !== 'object') return block

    switch (block.blockType) {
      case 'heroOfferV1':
        return {
          ...block,
          headline: normalizeRichTextValue(block.headline),
          subheadline: normalizeRichTextValue(block.subheadline),
        }

      case 'contentListV1':
        return {
          ...block,
          heading: normalizeRichTextValue(block.heading),
          items: Array.isArray(block.items)
            ? block.items.map((item) => ({
                ...item,
                eyebrow: normalizeRichTextValue(item.eyebrow),
                title: normalizeRichTextValue(item.title),
                subline: normalizeRichTextValue(item.subline),
                body: normalizeRichTextValue(item.body),
              }))
            : block.items,
        }

      case 'ctaBannerV1':
        return {
          ...block,
          headline: normalizeRichTextValue(block.headline),
        }

      case 'leadFormV1':
        return {
          ...block,
          heading: normalizeRichTextValue(block.heading),
        }

      case 'testimonial':
        return {
          ...block,
          heading: normalizeRichTextValue(block.heading),
          items: Array.isArray(block.items)
            ? block.items.map((item) => ({
                ...item,
                quote: normalizeRichTextValue(item.quote),
              }))
            : block.items,
        }

      case 'richTextV1':
        return {
          ...block,
          content: normalizeRichTextValue(block.content),
        }

      default:
        return block
    }
  })
}

export const normalizeLegacyPageRichText: CollectionAfterReadHook<Page> = async ({ doc }) => {
  if (!doc || typeof doc !== 'object') return doc

  doc.layout = normalizeLayout(doc.layout)

  return doc
}
