import type { CollectionConfig } from 'payload'
import { authenticatedOnly, tenantScopedPublicRead } from '../lib/tenantAccess'
import { parseVideoUrl, parseDuration, formatDuration } from '../lib/video'
import { createSlugValidationHook } from '../lib/validation'

/**
 * Videos Collection
 *
 * Zentrale Video-Bibliothek mit Unterstützung für:
 * - Direkte Video-Uploads
 * - YouTube Embeds
 * - Vimeo Embeds
 * - Externe Video-URLs
 */
export const Videos: CollectionConfig = {
  slug: 'videos',
  admin: {
    useAsTitle: 'title',
    group: 'Medien',
    description: 'Video-Bibliothek für YouTube/Vimeo Embeds und hochgeladene Videos',
    defaultColumns: ['title', 'source', 'category', 'status', 'publishedAt'],
  },
  access: {
    read: tenantScopedPublicRead,
    create: authenticatedOnly,
    update: authenticatedOnly,
    delete: authenticatedOnly,
  },
  fields: [
    // === HAUPTINFOS ===
    {
      name: 'title',
      type: 'text',
      required: true,
      localized: true,
      label: 'Titel',
      admin: {
        description: 'Titel des Videos',
      },
    },
    {
      name: 'slug',
      type: 'text',
      required: true,
      unique: false, // Uniqueness per tenant
      label: 'URL-Slug',
      admin: {
        description: 'URL-freundlicher Name (z.B. "produkt-tutorial")',
      },
    },
    {
      name: 'description',
      type: 'richText',
      localized: true,
      label: 'Beschreibung',
      admin: {
        description: 'Ausführliche Beschreibung des Videos',
      },
    },
    {
      name: 'excerpt',
      type: 'textarea',
      maxLength: 300,
      localized: true,
      label: 'Kurzfassung',
      admin: {
        description: 'Kurzbeschreibung für Übersichten (max. 300 Zeichen)',
      },
    },

    // === VIDEO-QUELLE ===
    {
      name: 'source',
      type: 'select',
      required: true,
      defaultValue: 'youtube',
      label: 'Video-Quelle',
      options: [
        { label: 'YouTube', value: 'youtube' },
        { label: 'Vimeo', value: 'vimeo' },
        { label: 'Video-Upload', value: 'upload' },
        { label: 'Externe URL', value: 'external' },
      ],
      admin: {
        description: 'Woher stammt das Video?',
      },
    },
    {
      name: 'videoFile',
      type: 'upload',
      relationTo: 'media',
      label: 'Video-Datei',
      admin: {
        description: 'MP4, WebM oder andere Video-Dateien',
        condition: (_, siblingData) => siblingData?.source === 'upload',
      },
    },
    {
      name: 'embedUrl',
      type: 'text',
      label: 'Video-URL',
      admin: {
        description: 'YouTube/Vimeo URL oder direkte Video-URL',
        condition: (_, siblingData) =>
          siblingData?.source === 'youtube' ||
          siblingData?.source === 'vimeo' ||
          siblingData?.source === 'external',
      },
    },
    {
      name: 'videoId',
      type: 'text',
      label: 'Video-ID',
      admin: {
        readOnly: true,
        description: 'Wird automatisch aus der URL extrahiert',
        condition: (_, siblingData) =>
          siblingData?.source === 'youtube' || siblingData?.source === 'vimeo',
      },
    },

    // === MEDIEN ===
    {
      name: 'thumbnail',
      type: 'upload',
      relationTo: 'media',
      label: 'Vorschaubild',
      admin: {
        description: 'Eigenes Thumbnail (bei YouTube wird automatisch eins verwendet falls leer)',
      },
    },
    {
      name: 'duration',
      type: 'text',
      label: 'Dauer',
      admin: {
        description: 'Video-Dauer (z.B. "2:30" oder "1:02:30")',
      },
    },
    {
      name: 'durationSeconds',
      type: 'number',
      label: 'Dauer (Sekunden)',
      admin: {
        readOnly: true,
        position: 'sidebar',
        description: 'Automatisch berechnet',
      },
    },

    // === KATEGORISIERUNG ===
    {
      name: 'category',
      type: 'relationship',
      relationTo: 'video-categories',
      label: 'Kategorie',
      admin: {
        description: 'Primäre Video-Kategorie',
      },
    },
    {
      name: 'tags',
      type: 'relationship',
      relationTo: 'tags',
      hasMany: true,
      label: 'Tags',
      admin: {
        description: 'Schlagwörter für bessere Auffindbarkeit',
      },
    },
    {
      name: 'videoType',
      type: 'select',
      label: 'Video-Typ',
      defaultValue: 'other',
      options: [
        { label: 'Tutorial', value: 'tutorial' },
        { label: 'Produktvideo', value: 'product' },
        { label: 'Testimonial', value: 'testimonial' },
        { label: 'Erklärvideo', value: 'explainer' },
        { label: 'Webinar', value: 'webinar' },
        { label: 'Interview', value: 'interview' },
        { label: 'Event', value: 'event' },
        { label: 'Trailer', value: 'trailer' },
        { label: 'Sonstiges', value: 'other' },
      ],
      admin: {
        position: 'sidebar',
        description: 'Art des Videos',
      },
    },

    // === WIEDERGABE-OPTIONEN ===
    {
      name: 'playback',
      type: 'group',
      label: 'Wiedergabe-Optionen',
      fields: [
        {
          name: 'autoplay',
          type: 'checkbox',
          defaultValue: false,
          label: 'Autoplay',
          admin: {
            description: 'Video automatisch starten (Browser blockieren oft ohne Mute)',
          },
        },
        {
          name: 'muted',
          type: 'checkbox',
          defaultValue: false,
          label: 'Stummgeschaltet',
          admin: {
            description: 'Video stumm abspielen (erforderlich für Autoplay in Browsern)',
          },
        },
        {
          name: 'loop',
          type: 'checkbox',
          defaultValue: false,
          label: 'Wiederholen',
          admin: {
            description: 'Video in Endlosschleife abspielen',
          },
        },
        {
          name: 'controls',
          type: 'checkbox',
          defaultValue: true,
          label: 'Steuerung anzeigen',
          admin: {
            description: 'Video-Controls anzeigen',
          },
        },
        {
          name: 'startTime',
          type: 'number',
          min: 0,
          label: 'Startzeit (Sekunden)',
          admin: {
            description: 'Video ab dieser Sekunde starten',
          },
        },
      ],
    },

    // === DARSTELLUNG ===
    {
      name: 'aspectRatio',
      type: 'select',
      defaultValue: '16:9',
      label: 'Seitenverhältnis',
      options: [
        { label: '16:9 (Standard)', value: '16:9' },
        { label: '4:3', value: '4:3' },
        { label: '1:1 (Quadrat)', value: '1:1' },
        { label: '9:16 (Vertikal)', value: '9:16' },
        { label: '21:9 (Ultrawide)', value: '21:9' },
      ],
      admin: {
        position: 'sidebar',
        description: 'Anzeigeverhältnis des Videos',
      },
    },

    // === STATUS & PUBLISHING ===
    {
      name: 'status',
      type: 'select',
      defaultValue: 'draft',
      label: 'Status',
      options: [
        { label: 'Entwurf', value: 'draft' },
        { label: 'Veröffentlicht', value: 'published' },
        { label: 'Archiviert', value: 'archived' },
      ],
      admin: {
        position: 'sidebar',
      },
    },
    {
      name: 'isFeatured',
      type: 'checkbox',
      defaultValue: false,
      label: 'Hervorgehoben',
      admin: {
        position: 'sidebar',
        description: 'Als Featured Video markieren',
      },
    },
    {
      name: 'publishedAt',
      type: 'date',
      label: 'Veröffentlichungsdatum',
      admin: {
        position: 'sidebar',
        date: {
          pickerAppearance: 'dayAndTime',
        },
      },
    },

    // === VERKNÜPFUNGEN ===
    {
      name: 'relatedVideos',
      type: 'relationship',
      relationTo: 'videos',
      hasMany: true,
      label: 'Verwandte Videos',
      admin: {
        description: 'Weitere Videos zu diesem Thema',
      },
    },
    {
      name: 'relatedPosts',
      type: 'relationship',
      relationTo: 'posts',
      hasMany: true,
      label: 'Verwandte Beiträge',
      admin: {
        description: 'Blog-Beiträge zu diesem Video',
      },
    },

    // === TRANSCRIPT ===
    {
      name: 'transcript',
      type: 'richText',
      localized: true,
      label: 'Transkript',
      admin: {
        description: 'Vollständiges Transkript für SEO und Barrierefreiheit',
      },
    },

    // === SEO ===
    {
      name: 'seo',
      type: 'group',
      label: 'SEO',
      fields: [
        {
          name: 'metaTitle',
          type: 'text',
          localized: true,
          label: 'Meta-Titel',
          admin: {
            description: 'SEO-Titel (falls abweichend vom Video-Titel)',
          },
        },
        {
          name: 'metaDescription',
          type: 'textarea',
          maxLength: 160,
          label: 'Meta-Beschreibung',
          admin: {
            description: 'SEO-Beschreibung (max. 160 Zeichen)',
          },
        },
        {
          name: 'ogImage',
          type: 'upload',
          relationTo: 'media',
          label: 'Social Media Bild',
          admin: {
            description: 'Bild für Social Media Shares (Fallback: Thumbnail)',
          },
        },
      ],
    },
  ],
  hooks: {
    beforeValidate: [
      createSlugValidationHook({ collection: 'videos' }),
    ],
    beforeChange: [
      ({ data }) => {
        if (!data) return data

        // Auto-Slug generieren falls leer
        if (!data.slug && data.title) {
          data.slug = data.title
            .toLowerCase()
            .replace(/[äöüß]/g, (char: string) => {
              const map: Record<string, string> = { ä: 'ae', ö: 'oe', ü: 'ue', ß: 'ss' }
              return map[char] || char
            })
            .replace(/[^a-z0-9]+/g, '-')
            .replace(/^-|-$/g, '')
        }

        // Video-ID aus URL extrahieren
        if (data.embedUrl && (data.source === 'youtube' || data.source === 'vimeo')) {
          const videoInfo = parseVideoUrl(data.embedUrl)
          if (videoInfo?.videoId) {
            data.videoId = videoInfo.videoId
          }
        }

        // Dauer zu Sekunden konvertieren
        if (data.duration) {
          data.durationSeconds = parseDuration(data.duration)
          // Dauer normalisieren
          if (data.durationSeconds > 0) {
            data.duration = formatDuration(data.durationSeconds)
          }
        }

        return data
      },
    ],
  },
}
