import type { CollectionConfig } from 'payload'

/**
 * Bookings Collection
 *
 * Terminbuchungen für Fotoshootings (porwoll.de)
 * Ermöglicht Kunden die Online-Buchung von Terminen.
 */
export const Bookings: CollectionConfig = {
  slug: 'bookings',
  labels: {
    singular: 'Buchung',
    plural: 'Buchungen',
  },
  admin: {
    group: 'Buchungen',
    useAsTitle: 'customerName',
    defaultColumns: ['customerName', 'service', 'date', 'status', 'createdAt'],
    description: 'Terminbuchungen für Fotoshootings',
  },
  access: {
    // Öffentlich erstellen (für Buchungsformular)
    create: () => true,
    // Nur authentifizierte Benutzer können lesen
    read: ({ req: { user } }) => {
      if (!user) return false
      if (user.isSuperAdmin) return true
      return {
        tenant: {
          equals: user.tenants?.[0]?.tenant,
        },
      }
    },
    update: ({ req: { user } }) => {
      if (!user) return false
      if (user.isSuperAdmin) return true
      return {
        tenant: {
          equals: user.tenants?.[0]?.tenant,
        },
      }
    },
    delete: ({ req: { user } }) => {
      if (!user) return false
      if (user.isSuperAdmin) return true
      return {
        tenant: {
          equals: user.tenants?.[0]?.tenant,
        },
      }
    },
  },
  fields: [
    // Kundendaten
    {
      type: 'row',
      fields: [
        {
          name: 'customerName',
          type: 'text',
          required: true,
          label: 'Name',
          admin: {
            width: '50%',
          },
        },
        {
          name: 'customerEmail',
          type: 'email',
          required: true,
          label: 'E-Mail',
          admin: {
            width: '50%',
          },
        },
      ],
    },
    {
      type: 'row',
      fields: [
        {
          name: 'customerPhone',
          type: 'text',
          label: 'Telefon',
          admin: {
            width: '50%',
          },
        },
        {
          name: 'customerCompany',
          type: 'text',
          label: 'Firma',
          admin: {
            width: '50%',
          },
        },
      ],
    },
    // Service-Auswahl
    {
      name: 'serviceType',
      type: 'select',
      required: true,
      label: 'Service-Typ',
      options: [
        { label: 'Hochzeitsfotografie', value: 'wedding' },
        { label: 'Portraitfotografie', value: 'portrait' },
        { label: 'Business-Fotografie', value: 'business' },
        { label: 'Event-Fotografie', value: 'event' },
        { label: 'Produktfotografie', value: 'product' },
        { label: 'Familienfotografie', value: 'family' },
        { label: 'Newborn/Baby', value: 'newborn' },
        { label: 'Schwangerschaft', value: 'maternity' },
        { label: 'Immobilienfotografie', value: 'realestate' },
        { label: 'Sonstiges', value: 'other' },
      ],
    },
    {
      name: 'service',
      type: 'relationship',
      relationTo: 'services',
      label: 'Verknüpfter Service',
      admin: {
        description: 'Optional: Verknüpfung mit einem definierten Service',
      },
    },
    // Termin
    {
      type: 'row',
      fields: [
        {
          name: 'date',
          type: 'date',
          required: true,
          label: 'Datum',
          admin: {
            width: '50%',
            date: {
              pickerAppearance: 'dayOnly',
              displayFormat: 'dd.MM.yyyy',
            },
          },
        },
        {
          name: 'time',
          type: 'text',
          label: 'Uhrzeit',
          admin: {
            width: '50%',
            description: 'z.B. 14:00 Uhr',
          },
        },
      ],
    },
    {
      name: 'duration',
      type: 'select',
      label: 'Geschätzte Dauer',
      options: [
        { label: '30 Minuten', value: '30' },
        { label: '1 Stunde', value: '60' },
        { label: '2 Stunden', value: '120' },
        { label: '3 Stunden', value: '180' },
        { label: 'Halber Tag (4h)', value: '240' },
        { label: 'Ganzer Tag (8h)', value: '480' },
        { label: 'Nach Absprache', value: 'custom' },
      ],
    },
    // Location
    {
      name: 'locationType',
      type: 'select',
      label: 'Location-Typ',
      options: [
        { label: 'Studio', value: 'studio' },
        { label: 'Outdoor', value: 'outdoor' },
        { label: 'Beim Kunden', value: 'customer' },
        { label: 'Event-Location', value: 'event' },
        { label: 'Nach Absprache', value: 'tbd' },
      ],
    },
    {
      name: 'locationAddress',
      type: 'textarea',
      label: 'Adresse / Location-Details',
      admin: {
        condition: (data, siblingData) =>
          siblingData?.locationType && siblingData?.locationType !== 'studio',
      },
    },
    // Zusätzliche Informationen
    {
      name: 'participants',
      type: 'number',
      label: 'Anzahl Personen',
      min: 1,
      admin: {
        description: 'Wie viele Personen sollen fotografiert werden?',
      },
    },
    {
      name: 'message',
      type: 'textarea',
      label: 'Nachricht / Wünsche',
      admin: {
        description: 'Besondere Wünsche, Ideen oder Anmerkungen',
      },
    },
    {
      name: 'referenceImages',
      type: 'array',
      label: 'Referenzbilder',
      admin: {
        description: 'Beispielbilder für gewünschten Stil',
      },
      fields: [
        {
          name: 'image',
          type: 'upload',
          relationTo: 'media',
          label: 'Bild',
        },
        {
          name: 'note',
          type: 'text',
          label: 'Anmerkung',
        },
      ],
    },
    // Status & Workflow
    {
      name: 'status',
      type: 'select',
      required: true,
      defaultValue: 'pending',
      label: 'Status',
      options: [
        { label: 'Anfrage eingegangen', value: 'pending' },
        { label: 'In Prüfung', value: 'review' },
        { label: 'Bestätigt', value: 'confirmed' },
        { label: 'Anzahlung erhalten', value: 'deposit' },
        { label: 'Durchgeführt', value: 'completed' },
        { label: 'Storniert', value: 'cancelled' },
        { label: 'No-Show', value: 'noshow' },
      ],
      admin: {
        position: 'sidebar',
      },
    },
    {
      name: 'priority',
      type: 'select',
      defaultValue: 'normal',
      label: 'Priorität',
      options: [
        { label: 'Hoch', value: 'high' },
        { label: 'Normal', value: 'normal' },
        { label: 'Niedrig', value: 'low' },
      ],
      admin: {
        position: 'sidebar',
      },
    },
    // Preisgestaltung
    {
      name: 'pricing',
      type: 'group',
      label: 'Preisgestaltung',
      admin: {
        condition: (data) => data?.status && data?.status !== 'pending',
      },
      fields: [
        {
          name: 'estimatedPrice',
          type: 'number',
          label: 'Geschätzter Preis',
          admin: {
            description: 'In Euro',
          },
        },
        {
          name: 'finalPrice',
          type: 'number',
          label: 'Endpreis',
        },
        {
          name: 'depositAmount',
          type: 'number',
          label: 'Anzahlung',
        },
        {
          name: 'depositPaid',
          type: 'checkbox',
          label: 'Anzahlung bezahlt',
          defaultValue: false,
        },
        {
          name: 'fullyPaid',
          type: 'checkbox',
          label: 'Vollständig bezahlt',
          defaultValue: false,
        },
      ],
    },
    // Interne Notizen
    {
      name: 'internalNotes',
      type: 'array',
      label: 'Interne Notizen',
      admin: {
        description: 'Nur für interne Verwendung',
      },
      fields: [
        {
          name: 'note',
          type: 'textarea',
          required: true,
          label: 'Notiz',
        },
        {
          name: 'author',
          type: 'relationship',
          relationTo: 'users',
          label: 'Autor',
          admin: {
            readOnly: true,
          },
        },
        {
          name: 'createdAt',
          type: 'date',
          label: 'Erstellt am',
          admin: {
            readOnly: true,
            date: {
              pickerAppearance: 'dayAndTime',
            },
          },
        },
      ],
    },
    // Kontakthistorie
    {
      name: 'contactHistory',
      type: 'array',
      label: 'Kontakthistorie',
      fields: [
        {
          name: 'type',
          type: 'select',
          required: true,
          label: 'Art',
          options: [
            { label: 'E-Mail gesendet', value: 'email_sent' },
            { label: 'E-Mail erhalten', value: 'email_received' },
            { label: 'Anruf', value: 'call' },
            { label: 'WhatsApp', value: 'whatsapp' },
            { label: 'Persönlich', value: 'inperson' },
          ],
        },
        {
          name: 'summary',
          type: 'textarea',
          required: true,
          label: 'Zusammenfassung',
        },
        {
          name: 'date',
          type: 'date',
          label: 'Datum',
          admin: {
            date: {
              pickerAppearance: 'dayAndTime',
            },
          },
        },
      ],
    },
    // Zugewiesener Fotograf
    {
      name: 'assignedTo',
      type: 'relationship',
      relationTo: 'users',
      label: 'Zugewiesen an',
      admin: {
        position: 'sidebar',
      },
    },
    // Quelle der Buchung
    {
      name: 'source',
      type: 'select',
      label: 'Buchungsquelle',
      options: [
        { label: 'Website', value: 'website' },
        { label: 'Telefon', value: 'phone' },
        { label: 'E-Mail', value: 'email' },
        { label: 'Instagram', value: 'instagram' },
        { label: 'Facebook', value: 'facebook' },
        { label: 'Empfehlung', value: 'referral' },
        { label: 'Wiederkehrend', value: 'returning' },
        { label: 'Sonstiges', value: 'other' },
      ],
      admin: {
        position: 'sidebar',
      },
    },
    // Datenschutz
    {
      name: 'gdprConsent',
      type: 'checkbox',
      label: 'DSGVO-Einwilligung',
      defaultValue: false,
      admin: {
        position: 'sidebar',
        description: 'Kunde hat Datenschutzerklärung akzeptiert',
      },
    },
  ],
  timestamps: true,
  hooks: {
    beforeChange: [
      ({ data, req }) => {
        // Auto-set author for new notes
        if (data?.internalNotes && req.user) {
          data.internalNotes = data.internalNotes.map((note: Record<string, unknown>) => {
            if (!note.author) {
              note.author = req.user?.id
            }
            if (!note.createdAt) {
              note.createdAt = new Date().toISOString()
            }
            return note
          })
        }
        return data
      },
    ],
  },
}
