import type { CollectionConfig } from 'payload'
import { authenticatedOnly, tenantScopedPublicRead } from '../lib/tenantAccess'

/**
 * Locations Collection
 *
 * Firmenstandorte mit Adresse, Öffnungszeiten, Kontaktdaten und Kartenposition.
 * Tenant-scoped für Multi-Tenant-Betrieb.
 */
export const Locations: CollectionConfig = {
  slug: 'locations',
  labels: {
    singular: 'Standort',
    plural: 'Standorte',
  },
  admin: {
    useAsTitle: 'name',
    group: 'Content',
    defaultColumns: ['name', 'city', 'type', 'isMain', 'isActive'],
    description: 'Firmenstandorte und Niederlassungen',
  },
  access: {
    read: tenantScopedPublicRead,
    create: authenticatedOnly,
    update: authenticatedOnly,
    delete: authenticatedOnly,
  },
  fields: [
    // Basis-Informationen
    {
      name: 'name',
      type: 'text',
      required: true,
      label: 'Name',
      localized: true,
      admin: {
        description: 'z.B. "Hauptsitz München", "Filiale Hamburg"',
      },
    },
    {
      name: 'slug',
      type: 'text',
      required: true,
      unique: true,
      label: 'Slug',
      admin: {
        description: 'URL-freundlicher Identifier',
      },
    },
    {
      name: 'type',
      type: 'select',
      defaultValue: 'office',
      label: 'Typ',
      options: [
        { label: 'Hauptsitz', value: 'headquarters' },
        { label: 'Büro', value: 'office' },
        { label: 'Filiale', value: 'branch' },
        { label: 'Lager', value: 'warehouse' },
        { label: 'Showroom', value: 'showroom' },
        { label: 'Studio', value: 'studio' },
        { label: 'Praxis', value: 'practice' },
        { label: 'Werkstatt', value: 'workshop' },
      ],
    },
    {
      name: 'description',
      type: 'richText',
      label: 'Beschreibung',
      localized: true,
      admin: {
        description: 'Optionale Beschreibung des Standorts',
      },
    },
    {
      name: 'image',
      type: 'upload',
      relationTo: 'media',
      label: 'Bild',
      admin: {
        description: 'Foto des Gebäudes oder Standorts',
      },
    },
    // Adresse
    {
      name: 'address',
      type: 'group',
      label: 'Adresse',
      fields: [
        {
          name: 'street',
          type: 'text',
          required: true,
          label: 'Straße & Hausnummer',
        },
        {
          name: 'additionalLine',
          type: 'text',
          label: 'Adresszusatz',
          admin: {
            description: 'z.B. "Gebäude B, 3. Stock"',
          },
        },
        {
          name: 'zip',
          type: 'text',
          required: true,
          label: 'PLZ',
        },
        {
          name: 'city',
          type: 'text',
          required: true,
          label: 'Stadt',
        },
        {
          name: 'state',
          type: 'text',
          label: 'Bundesland/Region',
        },
        {
          name: 'country',
          type: 'text',
          defaultValue: 'Deutschland',
          label: 'Land',
        },
      ],
    },
    // Geo-Koordinaten
    {
      name: 'geo',
      type: 'group',
      label: 'Geo-Koordinaten',
      admin: {
        description: 'Für Kartenanzeige',
      },
      fields: [
        {
          name: 'lat',
          type: 'number',
          label: 'Breitengrad (Latitude)',
          admin: {
            step: 0.000001,
            description: 'z.B. 48.137154',
          },
        },
        {
          name: 'lng',
          type: 'number',
          label: 'Längengrad (Longitude)',
          admin: {
            step: 0.000001,
            description: 'z.B. 11.576124',
          },
        },
        {
          name: 'zoom',
          type: 'number',
          defaultValue: 15,
          min: 1,
          max: 20,
          label: 'Zoom-Level',
        },
      ],
    },
    // Kontaktdaten
    {
      name: 'contact',
      type: 'group',
      label: 'Kontaktdaten',
      fields: [
        {
          name: 'phone',
          type: 'text',
          label: 'Telefon',
        },
        {
          name: 'fax',
          type: 'text',
          label: 'Fax',
        },
        {
          name: 'email',
          type: 'email',
          label: 'E-Mail',
        },
        {
          name: 'website',
          type: 'text',
          label: 'Website',
          admin: {
            description: 'Falls abweichend von Hauptwebsite',
          },
        },
      ],
    },
    // Öffnungszeiten
    {
      name: 'hours',
      type: 'group',
      label: 'Öffnungszeiten',
      fields: [
        {
          name: 'display',
          type: 'textarea',
          label: 'Freitext-Anzeige',
          localized: true,
          admin: {
            description: 'z.B. "Mo-Fr: 9-18 Uhr, Sa: 10-14 Uhr"',
          },
        },
        {
          name: 'structured',
          type: 'array',
          label: 'Strukturierte Zeiten',
          admin: {
            description: 'Detaillierte Öffnungszeiten pro Tag',
            initCollapsed: true,
          },
          fields: [
            {
              name: 'day',
              type: 'select',
              required: true,
              label: 'Tag',
              options: [
                { label: 'Montag', value: 'monday' },
                { label: 'Dienstag', value: 'tuesday' },
                { label: 'Mittwoch', value: 'wednesday' },
                { label: 'Donnerstag', value: 'thursday' },
                { label: 'Freitag', value: 'friday' },
                { label: 'Samstag', value: 'saturday' },
                { label: 'Sonntag', value: 'sunday' },
              ],
            },
            {
              name: 'closed',
              type: 'checkbox',
              defaultValue: false,
              label: 'Geschlossen',
            },
            {
              name: 'open',
              type: 'text',
              label: 'Öffnet',
              admin: {
                condition: (_, siblingData) => !siblingData?.closed,
                description: 'z.B. "09:00"',
              },
            },
            {
              name: 'close',
              type: 'text',
              label: 'Schließt',
              admin: {
                condition: (_, siblingData) => !siblingData?.closed,
                description: 'z.B. "18:00"',
              },
            },
            {
              name: 'break',
              type: 'group',
              label: 'Mittagspause',
              admin: {
                condition: (_, siblingData) => !siblingData?.closed,
              },
              fields: [
                {
                  name: 'hasBreak',
                  type: 'checkbox',
                  defaultValue: false,
                  label: 'Mittagspause',
                },
                {
                  name: 'start',
                  type: 'text',
                  label: 'Von',
                  admin: {
                    condition: (_, siblingData) => siblingData?.hasBreak,
                  },
                },
                {
                  name: 'end',
                  type: 'text',
                  label: 'Bis',
                  admin: {
                    condition: (_, siblingData) => siblingData?.hasBreak,
                  },
                },
              ],
            },
          ],
        },
        {
          name: 'note',
          type: 'text',
          label: 'Hinweis',
          localized: true,
          admin: {
            description: 'z.B. "Termine nach Vereinbarung"',
          },
        },
      ],
    },
    // Anfahrt
    {
      name: 'directions',
      type: 'group',
      label: 'Anfahrt',
      fields: [
        {
          name: 'text',
          type: 'richText',
          label: 'Anfahrtsbeschreibung',
          localized: true,
        },
        {
          name: 'parking',
          type: 'text',
          label: 'Parkmöglichkeiten',
          localized: true,
        },
        {
          name: 'publicTransport',
          type: 'text',
          label: 'Öffentliche Verkehrsmittel',
          localized: true,
          admin: {
            description: 'z.B. "U-Bahn U3 Haltestelle Münchner Freiheit"',
          },
        },
        {
          name: 'accessibility',
          type: 'text',
          label: 'Barrierefreiheit',
          localized: true,
        },
      ],
    },
    // Services an diesem Standort
    {
      name: 'services',
      type: 'relationship',
      relationTo: 'services',
      hasMany: true,
      label: 'Services an diesem Standort',
      admin: {
        description: 'Welche Dienstleistungen werden hier angeboten?',
      },
    },
    // Team an diesem Standort
    {
      name: 'teamMembers',
      type: 'relationship',
      relationTo: 'team',
      hasMany: true,
      label: 'Team-Mitglieder',
      admin: {
        description: 'Mitarbeiter an diesem Standort',
      },
    },
    // Status & Sortierung
    {
      name: 'isMain',
      type: 'checkbox',
      defaultValue: false,
      label: 'Hauptstandort',
      admin: {
        position: 'sidebar',
        description: 'Als primärer Standort markieren',
      },
    },
    {
      name: 'isActive',
      type: 'checkbox',
      defaultValue: true,
      label: 'Aktiv',
      admin: {
        position: 'sidebar',
      },
    },
    {
      name: 'showInFooter',
      type: 'checkbox',
      defaultValue: false,
      label: 'Im Footer anzeigen',
      admin: {
        position: 'sidebar',
      },
    },
    {
      name: 'order',
      type: 'number',
      defaultValue: 0,
      label: 'Sortierung',
      admin: {
        position: 'sidebar',
      },
    },
  ],
  hooks: {
    beforeChange: [
      ({ data }) => {
        // Auto-generate slug from name if not provided
        if (data && !data.slug && data.name) {
          data.slug = data.name
            .toLowerCase()
            .replace(/[äöüß]/g, (match: string) => {
              const map: Record<string, string> = { ä: 'ae', ö: 'oe', ü: 'ue', ß: 'ss' }
              return map[match] || match
            })
            .replace(/[^a-z0-9]+/g, '-')
            .replace(/^-|-$/g, '')
        }
        return data
      },
    ],
  },
}
