import type { CollectionConfig } from 'payload';

import CallToActionBlock from '../../Components/blocks/CallToAction/config';
import HeroBlock  from '@/Components/blocks/HeroBlock/config';
import FeaturesBlock from '@/Components/blocks/FeaturesBlock/config';
import MediaBlock from '@/Components/blocks/MediaBlock/config';
import TestimonialBlock from '@/Components/blocks/TestimonialBlock/config';
import PricingBlock from '@/Components/blocks/PricingBlock/config';
import FAQBlock from '@/Components/blocks/FAQBlock/config';
import LogoCloudBlock from '@/Components/blocks/LogoCloudBlock/config';
import ContactFormBlock from '@/Components/blocks/ContactFormBlock/config';
import TextBlock from '@/Components/blocks/TextBlock/config';
import FeaturesBlockCentered from '@/Components/blocks/FeaturesBlockCentered/config';
import SingUpBlock from '@/Components/blocks/SignUp/config'
import BookDemoBlock from '@/Components/blocks/BookDemoBlock/config'
import SectionTitleBlock from '@/Components/blocks/SectionTitleBlock/config';
import FeaturedStudyBlock from '@/Components/blocks/FeaturedStudyBlock/config';
import CalendlyWidgetBlock from '@/Components/blocks/CalendlyWidgetBlock/config';
import { revalidatePage } from '../hooks/revalidatePage'

import { createBreadcrumbsField } from '@payloadcms/plugin-nested-docs';
import { slugField } from '../fields/slug/slug';
import { MetaDescriptionField, MetaImageField, MetaTitleField, OverviewField, PreviewField } from '@payloadcms/plugin-seo/fields';

const Pages: CollectionConfig = {
  slug: 'pages',
  defaultSort: ['parent', '-order'],
  admin: {
    defaultColumns: ['title', 'slug', 'url'], // 👈 show test column
    listSearchableFields: ['title', 'slug', 'url'],
    useAsTitle: 'title'
  },
  defaultPopulate: {
    title: true,
    slug: true,
    url:true
  },
  fields: [
    {
      name: 'title',
      type: 'text',
      required: true,
      localized: true
    },
    {
      type: 'tabs',
      tabs: [
        {
          label: 'Content',
          name: 'content',
          fields: [
            {
              type: 'blocks',
              name: 'Layout',
              blocks: [
                SectionTitleBlock,
                TextBlock,
                CallToActionBlock,
                HeroBlock,
                FeaturesBlock,
                FeaturesBlockCentered,
                MediaBlock,
                TestimonialBlock,
                PricingBlock,
                FAQBlock,
                LogoCloudBlock,
                ContactFormBlock,
                SingUpBlock,
                BookDemoBlock,
                FeaturedStudyBlock,
                CalendlyWidgetBlock,
              ],
              required: true
            }
          ]
        },
        {
          name: 'meta',
          label: 'SEO',
          fields: [
            OverviewField({
              titlePath: 'meta.title',
              descriptionPath: 'meta.description',
              imagePath: 'meta.image'
            }),
            MetaTitleField({
              hasGenerateFn: true
            }),
            MetaImageField({
              relationTo: 'media'
            }),
            MetaDescriptionField({}),
            PreviewField({
              hasGenerateFn: true,
              titlePath: 'meta.title',
              descriptionPath: 'meta.description'
            })
          ]
        },
          {
          label: 'Breadcrumbs',
          fields: [
              createBreadcrumbsField("pages"),
          ],
        },
      ]
    },

    ...slugField(),

    {
        name: 'url',
        type: 'text',
        admin: {
            position: 'sidebar',
            readOnly: true,
        },
        access: {
        read: () => true,
      },
    },
    {
      name: 'template',
      type: 'select',
      admin: {
        position: 'sidebar',
      },
      options: [
        {
          label: 'Default',
          value: 'default',
        },
        {
          label: 'Blank',
          value: 'blank',
        },
      ],
      defaultValue: 'default',
      required: true,
    },
    {
        name: 'parent',
        type: 'relationship',
        relationTo: 'pages',
        filterOptions: ({ id }) => {
            return {
                id: {
                    not_in: [id],
                },
            }
        },
        admin: {
            position: 'sidebar',
        },
    },
    {
      name: 'order',
      type: 'number',
      required: true,
      defaultValue: 0,
      admin: {
        position: 'sidebar',
        components: {
          Cell: '@/payload/fields/TableOrderCell#TableOrderCell'
        }
      }
    },
  ],
  hooks: {
    afterChange: [revalidatePage],
    beforeChange: [
        async ({ data, req }) => {
            const newData = { ...data };

            // If the document has a slug, generate the full URL
            if (newData.slug) {
                // If the page has a parent, fetch the parent's URL
                if (newData.parent) {
                    const parentPage = await req.payload.findByID({
                        collection: 'pages',
                        id: newData.parent,
                        depth: 0, // We only need the parent's data, not its relations
                    });

                    // Combine the parent's URL with the current page's slug
                    if (parentPage && parentPage.url) {
                        newData.url = `${parentPage.url}/${newData.slug}`;
                    } else {
                        // Fallback for root-level pages
                        newData.url = newData.slug;
                    }
                } else {
                    // If there is no parent, the URL is just the slug
                    newData.url = newData.slug;
                }
            } else  newData.url = "/";

            return newData; // Return the modified data to be saved
        }
    ]
  }
};

export default Pages;
