import type { CollectionConfig } from 'payload'
import slugify from 'slugify'

export const Archiv: CollectionConfig = {
    slug: 'archiv',
    labels: {
        singular: 'Quelle',
        plural: 'Quellen',
    },

    admin: {
        useAsTitle: 'displayTitle',
        defaultColumns: ['displayTitle', 'year', 'type', 'digitizationStatus'],
        description: 'Archiv aller Quellen und Literatur — verknüpfbar mit Artikeln.',
    },
    access: {
        read:   () => true,
        create: ({ req }) => ['admin', 'editor'].includes(req.user?.role ?? ''),
        update: ({ req }) => ['admin', 'editor'].includes(req.user?.role ?? ''),
        delete: ({ req }) => req.user?.role === 'admin',
    },
    hooks: {
        beforeValidate: [
            ({ data, req }) => {
                const locale = req.locale || 'de'
                if (data?.title && !data?.slug) {
                    let raw = slugify(data.title as string, {
                        lower: true,
                        strict: true,
                        locale,
                    })
                    data.slug = raw.replace(/^\{.*?"([^"]+)"\}$/, '$1')
                }
                return data
            },
        ],
        beforeChange: [
            ({ data }) => {
                const firstAuthor = data?.authors?.[0]
                const authorStr = firstAuthor
                    ? `${firstAuthor.lastName}${firstAuthor.firstName ? ', ' + firstAuthor.firstName : ''}`
                    : null
                const yearStr = data?.year ? `(${data.year})` : null
                data.displayTitle = [authorStr, yearStr, data?.title]
                    .filter(Boolean)
                    .join(' ')
                return data
            },
        ],
    },
    fields: [
        // ── Bibliographic metadata ────────────────────────────────────────
        {
            name: 'type',
            label: 'Quellentyp',
            type: 'select',
            required: true,
            defaultValue: 'book',
            admin: { position: 'sidebar' },
            options: [
                { label: 'Buch',                value: 'book' },
                { label: 'Buchkapitel',          value: 'chapter' },
                { label: 'Zeitschriftenartikel', value: 'journal' },
                { label: 'Dissertation',         value: 'thesis' },
                { label: 'Konferenzbeitrag',     value: 'conference' },
                { label: 'Webseite',             value: 'website' },
                { label: 'Archivdokument',       value: 'archive' },
                { label: 'Sonstiges',            value: 'other' },
            ],
        },
        {
            name: 'digitizationStatus',
            label: 'Digitalisierungsstatus',
            type: 'select',
            defaultValue: 'unknown',
            admin: { position: 'sidebar' },
            options: [
                { label: 'Unbekannt',             value: 'unknown' },
                { label: 'Nicht digitalisiert',   value: 'none' },
                { label: 'Teilweise verfügbar',   value: 'partial' },
                { label: 'Vollständig verfügbar', value: 'full' },
                { label: 'Verloren / vernichtet', value: 'lost' },
            ],
        },
        {
            name: 'accessRestriction',
            label: 'Zugangsbeschränkung',
            type: 'select',
            defaultValue: 'open',
            admin: { position: 'sidebar' },
            options: [
                { label: 'Öffentlich zugänglich', value: 'open' },
                { label: 'Eingeschränkt',          value: 'restricted' },
                { label: 'Nur vor Ort',            value: 'onsite' },
                { label: 'Nicht zugänglich',       value: 'closed' },
            ],
        },
        {
            name: 'slug',
            label: 'URL-Slug',
            type: 'text',
            unique: true,
            index: true,
            admin: {
                position: 'sidebar',
                description: 'Wird automatisch generiert.',
            },
        },
        {
            name: 'displayTitle',
            label: 'Anzeigetitel',
            type: 'text',
            unique: true,
            index: true,
            admin: {
                hidden: true,
            },
        },
        {
            name: 'title',
            label: 'Titel',
            type: 'text',
            required: true,
        },
        {
            name: 'authors',
            label: 'Autor(en)',
            type: 'array',
            admin: {
                description: 'Mehrere Autoren in der gewünschten Reihenfolge hinzufügen.',
            },
            fields: [
                {
                    name: 'lastName',
                    label: 'Nachname',
                    type: 'text',
                    required: true,
                },
                {
                    name: 'firstName',
                    label: 'Vorname',
                    type: 'text',
                },
            ],
        },
        {
            name: 'editors',
            label: 'Herausgeber(in)',
            type: 'array',
            admin: {
                condition: (data) => ['book', 'chapter', 'conference'].includes(data?.type),
                description: 'Mehrere Herausgeber in der gewünschten Reihenfolge hinzufügen.',
            },
            fields: [
                {
                    name: 'lastName',
                    label: 'Nachname',
                    type: 'text',
                    required: true,
                },
                {
                    name: 'firstName',
                    label: 'Vorname',
                    type: 'text',
                },
            ],
        },
        {
            name: 'year',
            label: 'Erscheinungsjahr',
            type: 'number',
        },
        {
            name: 'language',
            label: 'Sprache',
            type: 'select',
            options: [
                { label: 'Deutsch',     value: 'de' },
                { label: 'Englisch',    value: 'en' },
                { label: 'Ungarisch',   value: 'hu' },
                { label: 'Französisch', value: 'fr' },
                { label: 'Latein',      value: 'la' },
                { label: 'Sonstiges',   value: 'other' },
            ],
        },
        {
            name: 'abstract',
            label: 'Abstract',
            type: 'textarea',
            admin: {
                condition: (data) => ['journal', 'thesis', 'conference'].includes(data?.type),
                description: 'Kurze inhaltliche Zusammenfassung.',
            },
        },
        {
            name: 'tags',
            label: 'Schlagwörter',
            type: 'array',
            admin: {
                description: 'Thematische Schlagwörter für die Archivsuche, z.B. "Siedlungsgeschichte", "Pécs", "Sprache".',
            },
            fields: [
                {
                    name: 'tag',
                    label: 'Schlagwort',
                    type: 'text',
                    required: true,
                },
            ],
        },
        // ── Book ──────────────────────────────────────────────────────────
        {
            name: 'isbn',
            label: 'ISBN',
            type: 'text',
            admin: {
                condition: (data) => ['book', 'chapter'].includes(data?.type),
            },
        },
        // ── Book / Chapter / Thesis / Conference ──────────────────────────
        {
            name: 'publisher',
            label: 'Verlag',
            type: 'text',
            admin: {
                condition: (data) =>
                    ['book', 'chapter', 'thesis', 'conference'].includes(data?.type),
            },
        },
        {
            name: 'place',
            label: 'Erscheinungsort',
            type: 'text',
            admin: {
                condition: (data) =>
                    ['book', 'chapter', 'thesis', 'conference'].includes(data?.type),
            },
        },
        // ── Chapter ───────────────────────────────────────────────────────
        {
            name: 'bookTitle',
            label: 'Buchtitel (Sammelband)',
            type: 'text',
            admin: {
                condition: (data) => data?.type === 'chapter',
            },
        },
        // ── Journal ───────────────────────────────────────────────────────
        {
            name: 'journal',
            label: 'Zeitschrift',
            type: 'text',
            admin: {
                condition: (data) => data?.type === 'journal',
            },
        },
        {
            name: 'volume',
            label: 'Band',
            type: 'text',
            admin: {
                condition: (data) => data?.type === 'journal',
            },
        },
        {
            name: 'issue',
            label: 'Heft',
            type: 'text',
            admin: {
                condition: (data) => data?.type === 'journal',
            },
        },
        {
            name: 'issn',
            label: 'ISSN',
            type: 'text',
            admin: {
                condition: (data) => data?.type === 'journal',
            },
        },
        // ── Thesis ────────────────────────────────────────────────────────
        {
            name: 'institution',
            label: 'Institution / Universität',
            type: 'text',
            admin: {
                condition: (data) => data?.type === 'thesis',
            },
        },
        {
            name: 'thesisType',
            label: 'Art der Arbeit',
            type: 'select',
            options: [
                { label: 'Dissertation',         value: 'phd' },
                { label: 'Masterarbeit',         value: 'master' },
                { label: 'Bachelorarbeit',       value: 'bachelor' },
                { label: 'Habilitationsschrift', value: 'habil' },
            ],
            admin: {
                condition: (data) => data?.type === 'thesis',
            },
        },
        // ── Series (Book / Thesis) ─────────────────────────────────────────
        {
            name: 'series',
            label: 'Schriftenreihe',
            type: 'text',
            admin: {
                condition: (data) => ['thesis', 'book'].includes(data?.type),
            },
        },
        {
            name: 'seriesNumber',
            label: 'Nummer in der Reihe',
            type: 'text',
            admin: {
                condition: (data) => ['thesis', 'book'].includes(data?.type),
            },
        },
        // ── Archive document ──────────────────────────────────────────────
        {
            name: 'archiveCollection',
            label: 'Archiv / Bestand',
            type: 'text',
            admin: {
                condition: (data) => data?.type === 'archive',
                description: 'z.B. "Stadtarchiv Pécs, Grundbuch 1723"',
            },
        },
        // ── Shared ────────────────────────────────────────────────────────
        {
            name: 'pages',
            label: 'Seiten',
            type: 'text',
            admin: {
                condition: (data) =>
                    ['chapter', 'journal', 'conference'].includes(data?.type),
                description: 'z.B. "45–67"',
            },
        },
        {
            name: 'shelfMark',
            label: 'Signatur',
            type: 'text',
            admin: {
                description: 'Archiv- oder Bibliothekssignatur.',
            },
        },
        {
            name: 'physicalLocation',
            label: 'Physischer Standort',
            type: 'text',
            admin: {
                description: 'Name des Archivs oder der Bibliothek.',
            },
        },
        {
            name: 'doi',
            label: 'DOI',
            type: 'text',
            admin: {
                condition: (data) => ['journal', 'conference'].includes(data?.type),
            },
        },
        {
            name: 'externalUrl',
            label: 'Externe URL',
            type: 'text',
            admin: {
                description: 'Link zu Digitalia, Archiv-Portal, Google Books etc.',
            },
        },
        {
            name: 'accessed',
            label: 'Abgerufen am',
            type: 'date',
            admin: {
                condition: (data) => Boolean(data?.externalUrl),
                date: { pickerAppearance: 'dayOnly' },
            },
        },
        {
            name: 'file',
            label: 'Datei (PDF / Scan)',
            type: 'upload',
            relationTo: 'media',
            admin: {
                description: 'Digitalisat direkt hochladen, falls vorhanden.',
            },
        },
        {
            name: 'note',
            label: 'Anmerkung',
            type: 'textarea',
        },
    ],
}