import { Block, GlobalConfig } from 'payload'
import { isAdmin } from '@/collections/access/admin'
import { revalidateTag } from 'next/cache'
import { validateHref } from '@/globals/ValidateHref'

const SimpleItem: Block = {
  slug: 'simple-item',
  labels: {
    singular: 'Einfach',
    plural: 'Einfach'
  },
  fields: [
    {
      name: 'text',
      type: 'text',
      required: true
    },
    {
      name: 'href',
      type: 'text',
      label: 'Zieladresse',
      required: true,
      validate: validateHref,
    },
    {
      name: 'type',
      type: 'select',
      options: [
        {
          label: 'Standard',
          value: 'default'
        },
        {
          label: 'Button',
          value: 'button'
        }
      ],
      defaultValue: "default",
      required: true
    }
  ]
}

const MegaMenuItem: Block = {
  slug: 'mega-menu',
  fields: [
    {
      name: 'text',
      type: 'text',
      required: true,
    },
    {
      name: 'quote',
      label: "Bibelvers",
      type: 'text',
      required: true
    },
    {
      name: 'source',
      label: 'Bibelvers buch',
      type: 'text',
      required: true
    },
    {
      name: 'groups',
      label: 'Navigationsgruppen',
      type: 'array',
      fields: [
        {
          name: 'title',
          label: 'Titel',
          type: 'text',
          required: true,
        },
        {
          name: 'items',
          label: 'Elemente',
          type: 'array',
          fields: [
            {
              name: 'title',
              label: 'title',
              type: 'text',
              required: true,
            },
            {
              name: 'description',
              label: 'Beschreibung',
              type: 'text',
              maxLength: 100,
              required: true,
            },
            {
              name: 'href',
              label: 'Zieladresse',
              type: 'text',
              required: true,
              validate: validateHref,
            }
          ],
          required: true,
        }
      ],
      minRows: 1,
      maxRows: 5,
      required: true,
    }
  ]
}

export const MenuGlobal: GlobalConfig = {
  slug: 'menu',
  label: {
    de: 'Navigationsmenü'
  },
  admin: {
    description: "Hier können Sie die Einträge und die Reihenfolge der Hauptnavigation festlegen.",
    hidden: args => args.user?.roles === "user"
  },
  fields: [
    {
      name: 'leftItems',
      label: 'Elemente links',
      type: 'blocks',
      required: true,
      blocks: [
        SimpleItem,
        MegaMenuItem
      ]
    },
    {
      name: 'rightItems',
      label: 'Elemente Rechts',
      type: 'blocks',
      required: true,
      blocks: [
        SimpleItem,
        MegaMenuItem
      ]
    }
  ],
  access: {
    read: () => true,
    update: isAdmin()
  },
  hooks: {
    afterChange: [() => revalidateTag("menu")]
  }
}