import type { TextFieldSingleValidation } from 'payload'
import {
  // Text Formatting Features
  BoldFeature,
  ItalicFeature,
  UnderlineFeature,
  StrikethroughFeature,
  InlineCodeFeature,
  SubscriptFeature,
  SuperscriptFeature,

  // Block Features
  ParagraphFeature,
  HeadingFeature,

  // List Features
  UnorderedListFeature,
  OrderedListFeature,
  ChecklistFeature,

  // Table Feature (Experimental)
  EXPERIMENTAL_TableFeature,

  // Layout Features
  AlignFeature,
  IndentFeature,
  BlockquoteFeature,
  HorizontalRuleFeature,

  // Media & Link Features
  LinkFeature,
  UploadFeature,
  RelationshipFeature,

  // Toolbar Features
  InlineToolbarFeature,
  FixedToolbarFeature,

  // Core
  lexicalEditor,
  type LinkFields,
} from '@payloadcms/richtext-lexical'

export const defaultLexical = lexicalEditor({
  features: [
    // Essential Block Features
    ParagraphFeature(),
    HeadingFeature({
      enabledHeadingSizes: ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'],
    }),

    // Text Formatting
    BoldFeature(),
    ItalicFeature(),
    UnderlineFeature(),
    StrikethroughFeature(),
    InlineCodeFeature(),
    SubscriptFeature(),
    SuperscriptFeature(),

    // Lists - NOW INCLUDED!
    UnorderedListFeature(),
    OrderedListFeature(),
    ChecklistFeature(),

    // Tables - EXPERIMENTAL BUT FULLY FUNCTIONAL!
    EXPERIMENTAL_TableFeature(),

    // Layout & Structure
    AlignFeature(),
    IndentFeature(),
    BlockquoteFeature(),
    HorizontalRuleFeature(),

    // Links with Custom Validation
    LinkFeature({
      enabledCollections: ['pages', 'posts'],
      fields: ({ defaultFields }) => {
        const defaultFieldsWithoutUrl = defaultFields.filter((field) => {
          if ('name' in field && field.name === 'url') return false
          return true
        })

        return [
          ...defaultFieldsWithoutUrl,
          {
            name: 'url',
            type: 'text',
            admin: {
              condition: (_data, siblingData) => siblingData?.linkType !== 'internal',
            },
            label: ({ t }) => t('fields:enterURL'),
            required: true,
            validate: ((value, options) => {
              if ((options?.siblingData as LinkFields)?.linkType === 'internal') {
                return true // no validation needed, as no url should exist for internal links
              }
              return value ? true : 'URL is required'
            }) as TextFieldSingleValidation,
          },
        ]
      },
    }),

    // Media Features
    UploadFeature({
      collections: {
        media: {
          fields: [
            {
              name: 'caption',
              type: 'richText',
              editor: lexicalEditor(),
            },
          ],
        },
      },
    }),

    RelationshipFeature({
      enabledCollections: ['pages', 'posts'],
    }),

    // Toolbar Features for Better UX
    InlineToolbarFeature(),
    FixedToolbarFeature(),
  ],
})
