import type { CollectionConfig } from 'payload'
import { notifyOnNewLead } from '../lib/leadMail'

const signedIn = ({ req }: { req: { user?: unknown } }) => Boolean(req.user)

// «سجّل اهتمامك»: every form sent from the pricing page. Visitors never read or write this collection
// directly; the form's server action validates and saves on their behalf.
export const Leads: CollectionConfig = {
  slug: 'leads',
  labels: { singular: { ar: 'طلب اهتمام', en: 'Interest request' }, plural: { ar: 'طلبات الاهتمام', en: 'Interest requests' } },
  admin: {
    useAsTitle: 'name',
    defaultColumns: ['name', 'phone', 'email', 'courseSlug', 'status', 'createdAt'],
    group: { ar: 'التسجيل', en: 'Enrolment' },
  },
  access: { read: signedIn, create: signedIn, update: signedIn, delete: signedIn },
  // a new request is mailed to the academy, so nobody has to watch this page to notice one
  hooks: { afterChange: [notifyOnNewLead] },
  defaultSort: '-createdAt',
  fields: [
    { name: 'name', type: 'text', required: true, label: { ar: 'الاسم', en: 'Name' } },
    { name: 'email', type: 'email', required: true, label: { ar: 'البريد', en: 'Email' } },
    { name: 'phone', type: 'text', label: { ar: 'الموبايل', en: 'Mobile' } },
    { name: 'role', type: 'text', label: { ar: 'الصفة', en: 'Role' } },
    { name: 'course', type: 'relationship', relationTo: 'courses', label: { ar: 'الدورة', en: 'Course' } },
    {
      name: 'courseSlug',
      type: 'text',
      label: { ar: 'معرّف الدورة', en: 'Course address' },
      admin: {
        readOnly: true,
        description: {
          ar: 'يُحفظ مع كل طلب، فيعرف المتابع الدورة حتى لو أُضيفت على المنصة ولم يُكتب لها صف هنا.',
          en: 'Kept with every request, so the course is known even when it was added on the platform and has no row here.',
        },
      },
    },
    { name: 'note', type: 'textarea', label: { ar: 'السؤال', en: 'Question' } },
    {
      type: 'row',
      fields: [
        {
          name: 'status',
          type: 'select',
          defaultValue: 'new',
          label: { ar: 'المتابعة', en: 'Follow-up' },
          options: [
            { value: 'new', label: { ar: 'جديد', en: 'New' } },
            { value: 'contacted', label: { ar: 'تم التواصل', en: 'Contacted' } },
            { value: 'enrolled', label: { ar: 'سجّل', en: 'Enrolled' } },
            { value: 'closed', label: { ar: 'مغلق', en: 'Closed' } },
          ],
        },
        {
          name: 'locale',
          type: 'select',
          label: { ar: 'لغة الصفحة', en: 'Page language' },
          options: [
            { value: 'ar', label: 'العربية' },
            { value: 'en', label: 'English' },
          ],
          admin: { readOnly: true },
        },
      ],
    },
  ],
}
