import type { CollectionConfig } from 'payload'
import { format, formatISO, parseISO } from 'date-fns'
import { isSuperAdmin } from '@/access/isSuperAdmin'
import { hasTenantRole } from '@/access/roles'

/**
 * Meal Orders Collection
 *
 * Represents a batch of meals for a specific date and meal type.
 * Caregivers create an order, add individual meals for residents, then submit to kitchen.
 *
 * Workflow:
 * 1. Caregiver creates an order (draft status)
 * 2. Caregiver adds individual meals for residents
 * 3. Caregiver reviews summary and submits (submitted status)
 * 4. Kitchen processes orders (preparing -> completed statuses)
 */
export const MealOrders: CollectionConfig = {
  slug: 'meal-orders',
  labels: {
    singular: 'Meal Order',
    plural: 'Meal Orders',
  },
  admin: {
    useAsTitle: 'title',
    description: 'Batch meals by date and meal type',
    defaultColumns: ['title', 'date', 'mealType', 'status', 'mealCount'],
    group: 'Meal Planning',
  },
  access: {
    // Admin and caregiver can create orders
    create: ({ req }) => {
      if (!req.user) return false
      if (isSuperAdmin(req.user)) return true
      return hasTenantRole(req.user, 'admin') || hasTenantRole(req.user, 'caregiver')
    },
    // All authenticated users within the tenant can read
    read: ({ req }) => {
      if (!req.user) return false
      return true // Multi-tenant plugin will filter by tenant
    },
    // Admin, caregiver (if draft), and kitchen can update
    update: ({ req }) => {
      if (!req.user) return false
      if (isSuperAdmin(req.user)) return true
      return (
        hasTenantRole(req.user, 'admin') ||
        hasTenantRole(req.user, 'caregiver') ||
        hasTenantRole(req.user, 'kitchen')
      )
    },
    // Only admin can delete
    delete: ({ req }) => {
      if (!req.user) return false
      if (isSuperAdmin(req.user)) return true
      return hasTenantRole(req.user, 'admin')
    },
  },
  fields: [
    {
      name: 'title',
      type: 'text',
      admin: {
        readOnly: true,
        description: 'Auto-generated title',
      },
      hooks: {
        beforeChange: [
          ({ data, operation }) => {
            if (operation === 'create' || operation === 'update') {
              const mealLabels: Record<string, string> = {
                breakfast: 'Breakfast',
                lunch: 'Lunch',
                dinner: 'Dinner',
              }
              const date = data?.date ? format(parseISO(data.date), 'EEE, MMM d') : ''
              const mealType = mealLabels[data?.mealType || ''] || data?.mealType || ''
              return `${mealType} - ${date}`
            }
            return data?.title
          },
        ],
      },
    },
    {
      type: 'row',
      fields: [
        {
          name: 'date',
          type: 'date',
          required: true,
          index: true,
          admin: {
            date: {
              pickerAppearance: 'dayOnly',
              displayFormat: 'yyyy-MM-dd',
            },
            width: '50%',
          },
        },
        {
          name: 'mealType',
          type: 'select',
          required: true,
          index: true,
          options: [
            { label: 'Breakfast (Frühstück)', value: 'breakfast' },
            { label: 'Lunch (Mittagessen)', value: 'lunch' },
            { label: 'Dinner (Abendessen)', value: 'dinner' },
          ],
          admin: {
            width: '50%',
          },
        },
      ],
    },
    {
      name: 'status',
      type: 'select',
      required: true,
      defaultValue: 'draft',
      index: true,
      options: [
        { label: 'Draft (In Progress)', value: 'draft' },
        { label: 'Submitted to Kitchen', value: 'submitted' },
        { label: 'Preparing', value: 'preparing' },
        { label: 'Completed', value: 'completed' },
      ],
      admin: {
        position: 'sidebar',
        description: 'Order status for workflow tracking',
      },
    },
    {
      name: 'mealCount',
      type: 'number',
      defaultValue: 0,
      admin: {
        position: 'sidebar',
        readOnly: true,
        description: 'Number of meals in this order',
      },
    },
    {
      name: 'submittedAt',
      type: 'date',
      admin: {
        position: 'sidebar',
        readOnly: true,
        description: 'When the order was submitted to kitchen',
        date: {
          pickerAppearance: 'dayAndTime',
        },
      },
    },
    {
      name: 'createdBy',
      type: 'relationship',
      relationTo: 'users',
      admin: {
        position: 'sidebar',
        readOnly: true,
        description: 'User who created this order',
      },
    },
    {
      name: 'notes',
      type: 'textarea',
      admin: {
        description: 'General notes for this batch of meals',
      },
    },
  ],
  hooks: {
    beforeChange: [
      // Set createdBy on create
      ({ req, operation, data }) => {
        if (operation === 'create' && req.user) {
          data.createdBy = req.user.id
        }
        // Set submittedAt when status changes to submitted
        if (data.status === 'submitted' && !data.submittedAt) {
          data.submittedAt = formatISO(new Date())
        }
        return data
      },
    ],
  },
}
