import type { CollectionConfig } from 'payload'

import {
  FixedToolbarFeature,
  HeadingFeature,
  InlineToolbarFeature,
  UploadFeature,
  lexicalEditor,
} from '@payloadcms/richtext-lexical'

import { authenticated } from '../../access/authenticated'
import { authenticatedOrPublished } from '../../access/authenticatedOrPublished'
import { affiliateUnlock } from '@/fields/affiliateUnlock'
import { revalidateChapter, revalidateDelete } from './hooks/revalidateChapter'

export const Chapters: CollectionConfig = {
  slug: 'chapters',
  access: {
    create: authenticated,
    delete: authenticated,
    read: authenticatedOrPublished,
    update: authenticated,
  },
  admin: {
    defaultColumns: ['title', 'story', 'chapterNumber', 'updatedAt'],
    useAsTitle: 'title',
    livePreview: {
      url: async ({ data, req }) => {
        if (!data?.slug) return null as any
        const storyId = typeof data.story === 'object' && data.story !== null
          ? (data.story as any).id
          : data.story
        if (!storyId) return null as any
        let storySlug: string | null = null
        try {
          const story = await (req.payload as any).findByID({
            collection: 'stories',
            id: storyId,
            depth: 0,
            overrideAccess: true,
            draft: true,
          })
          storySlug = story?.slug ?? null
        } catch {
          storySlug = null
        }
        if (!storySlug) return null as any
        const params = new URLSearchParams({
          path: `/truyen/${storySlug}/${data.slug as string}`,
          previewSecret: process.env.PREVIEW_SECRET || '',
        })
        return `/next/preview?${params.toString()}`
      },
    },
    preview: async (data, { req }) => {
      if (!data?.slug) return null as any
      const storyId = typeof (data as any).story === 'object' && (data as any).story !== null
        ? (data as any).story.id
        : (data as any).story
      if (!storyId) return null as any
      let storySlug: string | null = null
      try {
        const story = await (req.payload as any).findByID({
          collection: 'stories',
          id: storyId,
          depth: 0,
          overrideAccess: true,
          draft: true,
        })
        storySlug = story?.slug ?? null
      } catch {
        storySlug = null
      }
      if (!storySlug) return null as any
      const params = new URLSearchParams({
        path: `/truyen/${storySlug}/${data.slug as string}`,
        previewSecret: process.env.PREVIEW_SECRET || '',
      })
      return `/next/preview?${params.toString()}`
    },
  },
  fields: [
    {
      name: 'title',
      type: 'text',
      required: true,
      label: 'Tiêu đề chương',
    },
    {
      name: 'chapterNumber',
      type: 'number',
      required: true,
      label: 'Số chương',
      admin: { position: 'sidebar' },
    },
    {
      name: 'slug',
      type: 'text',
      label: 'Slug',
      admin: { readOnly: true, position: 'sidebar' },
      hooks: {
        beforeValidate: [
          ({ data, siblingData }) => {
            const num = data?.chapterNumber ?? siblingData?.chapterNumber
            if (num !== undefined && num !== null) {
              return `chuong-${num}`
            }
            return data?.slug
          },
        ],
      },
    },
    {
      name: 'story',
      type: 'relationship',
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      relationTo: 'stories' as any,
      required: true,
      label: 'Truyện',
      admin: { position: 'sidebar' },
    },
    {
      name: 'content',
      type: 'richText',
      required: true,
      label: 'Nội dung',
      editor: lexicalEditor({
        features: ({ rootFeatures }) => [
          ...rootFeatures,
          HeadingFeature({ enabledHeadingSizes: ['h2', 'h3', 'h4'] }),
          FixedToolbarFeature(),
          InlineToolbarFeature(),
          UploadFeature({
            collections: {
              media: { fields: [] },
            },
          }),
        ],
      }),
    },
    {
      name: 'publishedAt',
      type: 'date',
      label: 'Ngày đăng',
      admin: {
        date: { pickerAppearance: 'dayAndTime' },
        position: 'sidebar',
      },
      hooks: {
        beforeChange: [
          ({ siblingData, value }) => {
            if (siblingData._status === 'published' && !value) {
              return new Date()
            }
            return value
          },
        ],
      },
    },
    affiliateUnlock(),
  ],
  hooks: {
    afterChange: [revalidateChapter],
    afterDelete: [revalidateDelete],
  },
  versions: {
    drafts: {
      autosave: { interval: 100 },
    },
    maxPerDoc: 10,
  },
}
