// src/collections/YouTubeContent.ts

import type { CollectionConfig } from 'payload'
import {
  hasYouTubeAccess,
  isYouTubeCreatorOrAbove,
  isYouTubeManager,
  canAccessAssignedContent,
} from '../lib/youtubeAccess'
import { createTasksOnStatusChange } from '../hooks/youtubeContent/createTasksOnStatusChange'
import { downloadThumbnail } from '../hooks/youtubeContent/downloadThumbnail'
import { autoStatusTransitions } from '../hooks/youtubeContent/autoStatusTransitions'
// TODO: ScriptSectionBlock causes admin UI rendering issues
// import { ScriptSectionBlock } from '../blocks/ScriptSectionBlock'

/**
 * YouTubeContent Collection
 *
 * Content-Pipeline für YouTube-Videos mit Workflow-Status,
 * Freigaben, Terminen und Performance-Tracking.
 * Teil des YouTube Operations Hub.
 */
export const YouTubeContent: CollectionConfig = {
  slug: 'youtube-content',
  labels: {
    singular: 'YouTube-Video',
    plural: 'YouTube-Videos',
  },
  admin: {
    useAsTitle: 'title',
    group: 'YouTube',
    defaultColumns: ['title', 'channel', 'status', 'format', 'scheduledPublishDate', 'assignedTo'],
    listSearchableFields: ['title', 'description'],
    description: 'Content-Pipeline für YouTube-Videos',
  },
  access: {
    read: canAccessAssignedContent,
    create: isYouTubeCreatorOrAbove,
    update: canAccessAssignedContent,
    delete: isYouTubeManager,
  },
  hooks: {
    afterChange: [createTasksOnStatusChange, downloadThumbnail, autoStatusTransitions],
    beforeChange: [
      // Auto-Slug generieren
      ({ data }) => {
        if (!data) return data

        if (!data.slug && data.title) {
          const title = typeof data.title === 'string' ? data.title : data.title?.de || data.title?.en || ''
          data.slug = 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, '')
        }

        return data
      },
      // CreatedBy setzen
      ({ data, req, operation }) => {
        if (!data) return data
        if (operation === 'create' && req.user) {
          data.createdBy = req.user.id
        }
        return data
      },
    ],
  },
  fields: [
    // === GRUNDDATEN ===
    {
      name: 'title',
      type: 'text',
      required: true,
      localized: true,
      label: 'Titel',
      maxLength: 100,
      admin: {
        description: 'Max. 60 Zeichen für YouTube empfohlen',
      },
    },
    {
      name: 'slug',
      type: 'text',
      required: true,
      label: 'Slug',
      admin: {
        description: 'URL-freundlicher Name (wird automatisch generiert)',
      },
    },
    {
      name: 'channel',
      type: 'relationship',
      relationTo: 'youtube-channels',
      required: true,
      label: 'Kanal',
      admin: {
        position: 'sidebar',
      },
    },
    {
      name: 'series',
      type: 'relationship',
      relationTo: 'yt-series',
      label: 'Serie',
      filterOptions: ({ data }) => {
        if (data?.channel) {
          return {
            channel: {
              equals: typeof data.channel === 'object' ? data.channel.id : data.channel,
            },
          }
        }
        return true
      },
      admin: {
        position: 'sidebar',
        description: 'Content-Serie für dieses Video',
      },
    },
    {
      name: 'format',
      type: 'select',
      required: true,
      label: 'Format',
      options: [
        { label: 'Short (< 60s)', value: 'short' },
        { label: 'Longform', value: 'longform' },
        { label: 'Premiere/Live', value: 'premiere' },
      ],
      admin: {
        position: 'sidebar',
      },
    },

    // === STATUS & WORKFLOW ===
    {
      name: 'status',
      type: 'select',
      required: true,
      defaultValue: 'idea',
      label: 'Status',
      options: [
        { label: 'Idee', value: 'idea' },
        { label: 'Skript in Arbeit', value: 'script_draft' },
        { label: 'Skript Review', value: 'script_review' },
        { label: 'Skript freigegeben', value: 'script_approved' },
        { label: 'Dreh geplant', value: 'shoot_scheduled' },
        { label: 'Gedreht', value: 'shot' },
        { label: 'Rohschnitt', value: 'rough_cut' },
        { label: 'Feinschnitt', value: 'fine_cut' },
        { label: 'Final Review', value: 'final_review' },
        { label: 'Freigegeben', value: 'approved' },
        { label: 'Upload geplant', value: 'upload_scheduled' },
        { label: 'Live', value: 'published' },
        { label: 'Performance getrackt', value: 'tracked' },
        { label: 'Verworfen', value: 'discarded' },
      ],
      admin: {
        position: 'sidebar',
      },
    },
    {
      name: 'priority',
      type: 'select',
      defaultValue: 'normal',
      label: 'Priorität',
      options: [
        { label: 'Dringend', value: 'urgent' },
        { label: 'Hoch', value: 'high' },
        { label: 'Normal', value: 'normal' },
        { label: 'Niedrig', value: 'low' },
      ],
      admin: {
        position: 'sidebar',
      },
    },

    // === ZUWEISUNG ===
    {
      name: 'assignedTo',
      type: 'relationship',
      relationTo: 'users',
      label: 'Zugewiesen an',
      admin: {
        position: 'sidebar',
      },
    },
    {
      name: 'createdBy',
      type: 'relationship',
      relationTo: 'users',
      label: 'Erstellt von',
      admin: {
        readOnly: true,
        position: 'sidebar',
      },
    },
    {
      name: 'productionBatch',
      type: 'relationship',
      relationTo: 'yt-batches',
      label: { de: 'Produktions-Batch', en: 'Production Batch' },
      admin: {
        position: 'sidebar',
      },
    },

    // === TABS ===
    {
      type: 'tabs',
      tabs: [
        {
          label: 'Inhalt',
          fields: [
            {
              name: 'description',
              type: 'textarea',
              localized: true,
              label: 'Beschreibung / Konzept',
            },
            {
              name: 'hook',
              type: 'text',
              localized: true,
              label: 'Hook (erste 3 Sekunden)',
              admin: {
                description: 'Was sagt/zeigt der Creator in den ersten 3 Sekunden?',
              },
            },
            {
              name: 'keyPoints',
              type: 'array',
              label: 'Kernpunkte',
              fields: [{ name: 'point', type: 'text', localized: true, label: 'Punkt' }],
            },
            {
              name: 'callToAction',
              type: 'text',
              localized: true,
              label: 'Call-to-Action',
            },
            {
              name: 'scriptUrl',
              type: 'text',
              label: 'Skript-Link (Google Docs)',
            },
            {
              name: 'scriptContent',
              type: 'richText',
              localized: true,
              label: 'Skript (optional inline)',
            },
          ],
        },
        {
          label: 'Termine',
          fields: [
            {
              name: 'shootDate',
              type: 'date',
              label: 'Dreh-Datum',
              admin: {
                date: { pickerAppearance: 'dayAndTime' },
              },
            },
            {
              name: 'editDeadline',
              type: 'date',
              label: 'Schnitt-Deadline',
            },
            {
              name: 'reviewDeadline',
              type: 'date',
              label: 'Review-Deadline',
            },
            {
              name: 'scheduledPublishDate',
              type: 'date',
              label: 'Geplantes Veröffentlichungsdatum',
              admin: {
                date: { pickerAppearance: 'dayAndTime' },
              },
            },
            {
              name: 'actualPublishDate',
              type: 'date',
              label: 'Tatsächliches Veröffentlichungsdatum',
              admin: { readOnly: true },
            },
          ],
        },
        {
          label: { de: 'Produktion', en: 'Production' },
          fields: [
            {
              type: 'row',
              fields: [
                {
                  name: 'productionWeek',
                  type: 'number',
                  label: { de: 'Produktionswoche', en: 'Production Week' },
                  min: 1,
                  max: 52,
                  admin: { width: '50%' },
                },
                {
                  name: 'calendarWeek',
                  type: 'number',
                  label: { de: 'Kalenderwoche', en: 'Calendar Week' },
                  min: 1,
                  max: 52,
                  admin: { width: '50%' },
                },
              ],
            },
            {
              name: 'productionDate',
              type: 'date',
              label: { de: 'Produktionsdatum', en: 'Production Date' },
              admin: {
                date: {
                  pickerAppearance: 'dayOnly',
                  displayFormat: 'dd.MM.yyyy',
                },
              },
            },
            {
              name: 'targetDuration',
              type: 'text',
              label: { de: 'Ziel-Dauer', en: 'Target Duration' },
              admin: {
                placeholder: 'z.B. "8-12 Min" oder "45-58s"',
              },
            },
            {
              name: 'bRollNotes',
              type: 'textarea',
              label: { de: 'B-Roll / Setting Notizen', en: 'B-Roll / Setting Notes' },
              localized: true,
              admin: {
                rows: 3,
              },
            },
          ],
        },
        // TODO: Script tab disabled - ScriptSectionBlock causes admin UI rendering issues
        // {
        //   label: 'Script',
        //   fields: [
        //     {
        //       name: 'script',
        //       type: 'blocks',
        //       label: { de: 'Script Sections', en: 'Script Sections' },
        //       labels: {
        //         singular: { de: 'Section', en: 'Section' },
        //         plural: { de: 'Script Sections', en: 'Script Sections' },
        //       },
        //       blocks: [ScriptSectionBlock],
        //       admin: {
        //         description: { de: 'Strukturiertes Video-Script mit Sections', en: 'Structured video script with sections' },
        //       },
        //     },
        //   ],
        // },
        {
          label: 'Posting',
          fields: [
            {
              name: 'publishTime',
              type: 'text',
              label: { de: 'Posting-Uhrzeit', en: 'Publish Time' },
              admin: {
                placeholder: 'z.B. "07:00" oder "17:00"',
              },
            },
            {
              name: 'thumbnailText',
              type: 'text',
              label: { de: 'Thumbnail-Text', en: 'Thumbnail Text' },
              admin: {
                placeholder: 'z.B. "BOARD READY | 7 MIN"',
              },
            },
            {
              type: 'row',
              fields: [
                {
                  name: 'ctaType',
                  type: 'select',
                  label: { de: 'CTA-Typ', en: 'CTA Type' },
                  options: [
                    { label: 'Link in Bio', value: 'link_in_bio' },
                    { label: 'Newsletter', value: 'newsletter' },
                    { label: { de: 'Longform verlinken', en: 'Link Longform' }, value: 'longform_link' },
                    { label: { de: 'Benutzerdefiniert', en: 'Custom' }, value: 'custom' },
                  ],
                  admin: { width: '50%' },
                },
                {
                  name: 'ctaDetail',
                  type: 'text',
                  label: { de: 'CTA-Detail', en: 'CTA Detail' },
                  admin: {
                    width: '50%',
                    placeholder: 'z.B. "GRFI-Checkliste"',
                    condition: (data) => !!data?.ctaType,
                  },
                },
              ],
            },
            {
              name: 'uploadChecklist',
              type: 'array',
              label: { de: 'Upload-Checkliste', en: 'Upload Checklist' },
              fields: [
                {
                  type: 'row',
                  fields: [
                    {
                      name: 'step',
                      type: 'text',
                      required: true,
                      label: { de: 'Schritt', en: 'Step' },
                      admin: { width: '60%' },
                    },
                    {
                      name: 'completed',
                      type: 'checkbox',
                      label: { de: 'Erledigt', en: 'Done' },
                      admin: { width: '20%' },
                    },
                    {
                      name: 'completedAt',
                      type: 'date',
                      label: { de: 'Am', en: 'At' },
                      admin: {
                        width: '20%',
                        readOnly: true,
                      },
                    },
                  ],
                },
              ],
            },
            {
              name: 'disclaimers',
              type: 'array',
              label: { de: 'Disclaimers', en: 'Disclaimers' },
              fields: [
                {
                  type: 'row',
                  fields: [
                    {
                      name: 'type',
                      type: 'select',
                      required: true,
                      label: { de: 'Typ', en: 'Type' },
                      options: [
                        { label: { de: 'Medizinisch', en: 'Medical' }, value: 'medical' },
                        { label: { de: 'Rechtlich', en: 'Legal' }, value: 'legal' },
                        { label: 'Affiliate', value: 'affiliate' },
                        { label: 'Sponsored', value: 'sponsored' },
                      ],
                      admin: { width: '25%' },
                    },
                    {
                      name: 'text',
                      type: 'text',
                      label: { de: 'Text', en: 'Text' },
                      localized: true,
                      admin: { width: '50%' },
                    },
                    {
                      name: 'placement',
                      type: 'select',
                      label: { de: 'Platzierung', en: 'Placement' },
                      options: [
                        { label: { de: 'Gesprochen', en: 'Spoken' }, value: 'spoken' },
                        { label: 'Text-Overlay', value: 'overlay' },
                        { label: { de: 'Beschreibung', en: 'Description' }, value: 'description' },
                        { label: { de: 'Überall', en: 'All' }, value: 'all' },
                      ],
                      admin: { width: '25%' },
                    },
                  ],
                },
              ],
            },
          ],
        },
        {
          label: 'Dateien',
          fields: [
            {
              name: 'thumbnail',
              type: 'upload',
              relationTo: 'media',
              label: 'Thumbnail',
            },
            {
              name: 'thumbnailAlt',
              type: 'upload',
              relationTo: 'media',
              label: 'Thumbnail (A/B-Test)',
            },
            {
              name: 'videoFile',
              type: 'upload',
              relationTo: 'media',
              label: 'Video-Datei (Final)',
            },
            {
              name: 'rawFootage',
              type: 'array',
              label: 'Rohmaterial',
              fields: [
                { name: 'file', type: 'upload', relationTo: 'media', label: 'Datei' },
                { name: 'description', type: 'text', label: 'Beschreibung' },
              ],
            },
          ],
        },
        {
          label: 'Freigaben',
          fields: [
            {
              name: 'approvals',
              type: 'group',
              label: 'Freigaben',
              fields: [
                {
                  name: 'scriptApproval',
                  type: 'group',
                  label: 'Skript-Freigabe',
                  fields: [
                    { name: 'approved', type: 'checkbox', label: 'Freigegeben' },
                    { name: 'approvedBy', type: 'relationship', relationTo: 'users', label: 'Von' },
                    { name: 'approvedAt', type: 'date', label: 'Am' },
                    { name: 'notes', type: 'textarea', localized: true, label: 'Anmerkungen' },
                  ],
                },
                {
                  name: 'medicalApproval',
                  type: 'group',
                  label: 'Medizinische Freigabe',
                  admin: {
                    description: 'Nur für Corporate-Kanäle relevant',
                  },
                  fields: [
                    { name: 'required', type: 'checkbox', label: 'Erforderlich', defaultValue: false },
                    { name: 'approved', type: 'checkbox', label: 'Freigegeben' },
                    { name: 'approvedBy', type: 'relationship', relationTo: 'users', label: 'Von' },
                    { name: 'approvedAt', type: 'date', label: 'Am' },
                    { name: 'notes', type: 'textarea', localized: true, label: 'Anmerkungen' },
                  ],
                },
                {
                  name: 'legalApproval',
                  type: 'group',
                  label: 'Rechtliche Freigabe',
                  fields: [
                    { name: 'approved', type: 'checkbox', label: 'Freigegeben' },
                    { name: 'approvedBy', type: 'relationship', relationTo: 'users', label: 'Von' },
                    { name: 'approvedAt', type: 'date', label: 'Am' },
                    { name: 'disclaimerIncluded', type: 'checkbox', label: 'Disclaimer enthalten' },
                    { name: 'notes', type: 'textarea', localized: true, label: 'Anmerkungen' },
                  ],
                },
                {
                  name: 'finalApproval',
                  type: 'group',
                  label: 'Finale Freigabe',
                  fields: [
                    { name: 'approved', type: 'checkbox', label: 'Freigegeben' },
                    { name: 'approvedBy', type: 'relationship', relationTo: 'users', label: 'Von' },
                    { name: 'approvedAt', type: 'date', label: 'Am' },
                    { name: 'notes', type: 'textarea', localized: true, label: 'Anmerkungen' },
                  ],
                },
              ],
            },
          ],
        },
        {
          label: 'YouTube',
          fields: [
            {
              name: 'youtube',
              type: 'group',
              label: 'YouTube-Daten',
              fields: [
                { name: 'videoId', type: 'text', label: 'YouTube Video ID', admin: { readOnly: true } },
                { name: 'url', type: 'text', label: 'YouTube URL', admin: { readOnly: true } },
                {
                  name: 'metadata',
                  type: 'group',
                  label: 'Metadaten für Upload',
                  fields: [
                    { name: 'youtubeTitle', type: 'text', localized: true, label: 'YouTube-Titel', maxLength: 100 },
                    { name: 'youtubeDescription', type: 'textarea', localized: true, label: 'YouTube-Beschreibung' },
                    {
                      name: 'tags',
                      type: 'array',
                      label: 'Tags',
                      fields: [{ name: 'tag', type: 'text', label: 'Tag' }],
                    },
                    {
                      name: 'visibility',
                      type: 'select',
                      label: 'Sichtbarkeit',
                      options: [
                        { label: 'Öffentlich', value: 'public' },
                        { label: 'Nicht gelistet', value: 'unlisted' },
                        { label: 'Privat', value: 'private' },
                      ],
                      defaultValue: 'private',
                    },
                    { name: 'chapters', type: 'textarea', label: 'Kapitelmarker' },
                    { name: 'pinnedComment', type: 'textarea', localized: true, label: 'Gepinnter Kommentar' },
                  ],
                },
              ],
            },
          ],
        },
        {
          label: 'Performance',
          fields: [
            {
              name: 'performance',
              type: 'group',
              label: 'Performance-Metriken',
              admin: {
                description: 'Automatisch via YouTube API aktualisiert',
              },
              fields: [
                { name: 'views', type: 'number', label: 'Aufrufe', admin: { readOnly: true } },
                { name: 'likes', type: 'number', label: 'Likes', admin: { readOnly: true } },
                { name: 'comments', type: 'number', label: 'Kommentare', admin: { readOnly: true } },
                { name: 'shares', type: 'number', label: 'Shares', admin: { readOnly: true } },
                { name: 'watchTimeMinutes', type: 'number', label: 'Wiedergabezeit (Min)', admin: { readOnly: true } },
                { name: 'avgViewDuration', type: 'number', label: 'Ø Wiedergabedauer (Sek)', admin: { readOnly: true } },
                { name: 'avgViewPercentage', type: 'number', label: 'Ø Wiedergabe (%)', admin: { readOnly: true } },
                { name: 'ctr', type: 'number', label: 'CTR (%)', admin: { readOnly: true } },
                { name: 'impressions', type: 'number', label: 'Impressionen', admin: { readOnly: true } },
                { name: 'subscribersGained', type: 'number', label: 'Neue Abos', admin: { readOnly: true } },
                { name: 'lastSyncedAt', type: 'date', label: 'Letzter Sync', admin: { readOnly: true } },
              ],
            },
            {
              name: 'costs',
              type: 'group',
              label: 'Kosten & Einnahmen',
              admin: {
                description: 'Für ROI-Berechnung (manuell pflegen)',
              },
              fields: [
                {
                  name: 'estimatedProductionHours',
                  type: 'number',
                  label: 'Geschätzte Produktionsstunden',
                  min: 0,
                },
                {
                  name: 'estimatedProductionCost',
                  type: 'number',
                  label: 'Geschätzte Produktionskosten (EUR)',
                  min: 0,
                },
                {
                  name: 'estimatedRevenue',
                  type: 'number',
                  label: 'Geschätzte Einnahmen (EUR)',
                  min: 0,
                  admin: {
                    description: 'AdSense + Sponsoring + Affiliate',
                  },
                },
              ],
            },
          ],
        },
      ],
    },

    // === INTERNE NOTIZEN ===
    {
      name: 'internalNotes',
      type: 'richText',
      label: 'Interne Notizen',
      admin: {
        description: 'Nur für das Team sichtbar',
      },
    },
  ],
  timestamps: true,
}
