import { defineArrayMember, defineField, defineType } from 'sanity';
import { CalendarIcon } from '@sanity/icons/Calendar';
import { CogIcon } from '@sanity/icons/Cog';
import { DocumentTextIcon } from '@sanity/icons/DocumentText';
import { ComposeIcon } from '@sanity/icons/Compose';
import { LemonIcon } from '@sanity/icons/Lemon';
import { SparklesIcon } from '@sanity/icons/Sparkles';
import { PackageIcon } from '@sanity/icons/Package';
import { sectionTypes } from './sections';

const slug = (source = 'title') =>
  defineField({
    name: 'slug',
    title: 'כתובת באתר',
    type: 'slug',
    description: 'אותיות באנגלית ומקפים בלבד, למשל digestive-system. לחצי "Generate" או כתבי בעצמך.',
    options: { source, maxLength: 80, slugify: (s: string) => latinSlug(s) },
    validation: (r) => r.required(),
  });

/** Hebrew titles produce empty slugs; fall back to a dated slug she can edit. */
function latinSlug(input: string) {
  const s = input.toLowerCase().replace(/[^a-z0-9\s-]/g, '').trim().replace(/\s+/g, '-').slice(0, 80);
  return s || `post-${new Date().toISOString().slice(0, 10)}`;
}

const seoFields = [
  defineField({ name: 'seoTitle', title: 'כותרת לגוגל (לא חובה)', type: 'string', group: 'seo' }),
  defineField({ name: 'seoDescription', title: 'תיאור לגוגל ולשיתוף (לא חובה)', type: 'text', rows: 2, group: 'seo', validation: (r) => r.max(170) }),
];

export const siteSettings = defineType({
  name: 'siteSettings',
  title: 'הגדרות האתר',
  type: 'document',
  icon: CogIcon,
  groups: [
    { name: 'contact', title: 'פרטי קשר', default: true },
    { name: 'social', title: 'רשתות' },
    { name: 'content', title: 'תוכן משותף' },
  ],
  fields: [
    defineField({ name: 'title', title: 'שם האתר', type: 'string', group: 'contact' }),
    defineField({ name: 'ownerName', title: 'שם מלא', type: 'string', group: 'contact' }),
    defineField({ name: 'tagline', title: 'תיאור קצר', type: 'string', group: 'contact' }),
    defineField({ name: 'modalities', title: 'תחומי טיפול', type: 'array', of: [{ type: 'string' }], options: { layout: 'tags' }, group: 'contact' }),
    defineField({ name: 'description', title: 'תיאור האתר לגוגל', type: 'text', rows: 3, group: 'contact' }),
    defineField({ name: 'phone', title: 'טלפון', type: 'string', group: 'contact' }),
    defineField({ name: 'email', title: 'מייל', type: 'string', group: 'contact' }),
    defineField({ name: 'whatsappUrl', title: 'קישור וואטסאפ', type: 'url', group: 'contact' }),
    defineField({ name: 'location', title: 'מיקום', type: 'string', group: 'contact' }),
    defineField({
      name: 'social',
      title: 'קישורים',
      type: 'object',
      group: 'social',
      fields: [
        defineField({ name: 'instagram', title: 'אינסטגרם', type: 'url' }),
        defineField({ name: 'youtube', title: 'יוטיוב', type: 'url' }),
        defineField({ name: 'tiktok', title: 'טיקטוק', type: 'url' }),
        defineField({ name: 'facebook', title: 'פייסבוק – שנינה', type: 'url' }),
        defineField({ name: 'facebookMethod', title: 'פייסבוק – שיטת אי"ך', type: 'url' }),
        defineField({ name: 'facebookPersonal', title: 'פייסבוק – אישי', type: 'url' }),
        defineField({ name: 'telegram', title: 'טלגרם', type: 'url' }),
        defineField({ name: 'podcast', title: 'פודקאסט', type: 'url' }),
      ],
    }),
    defineField({ name: 'instagramHandle', title: 'שם משתמש באינסטגרם', type: 'string', group: 'social' }),
    defineField({
      name: 'principles',
      title: 'הנחות היסוד',
      description: 'מופיעות בעמוד הבית ובעמוד "מי אני"',
      type: 'array',
      group: 'content',
      of: [
        defineArrayMember({
          type: 'object',
          name: 'principle',
          fields: [defineField({ name: 'text', title: 'טקסט', type: 'simpleText' })],
          preview: {
            select: { blocks: 'text' },
            prepare: ({ blocks }) => ({ title: (blocks?.[0]?.children ?? []).map((c: any) => c.text).join('').slice(0, 80) || 'הנחת יסוד' }),
          },
        }),
      ],
    }),
    defineField({ name: 'medicalDisclaimer', title: 'הבהרה רפואית (בתחתית כל עמוד)', type: 'text', rows: 2, group: 'content' }),
  ],
  preview: { prepare: () => ({ title: 'הגדרות האתר' }) },
});

export const page = defineType({
  name: 'page',
  title: 'עמוד',
  type: 'document',
  icon: DocumentTextIcon,
  fields: [
    defineField({ name: 'title', title: 'שם העמוד', type: 'string', validation: (r) => r.required() }),
    slug(),
    defineField({ name: 'description', title: 'תיאור לגוגל ולשיתוף', type: 'text', rows: 2, validation: (r) => r.max(170) }),
    defineField({
      name: 'sections',
      title: 'חלקי העמוד',
      description: 'אפשר להוסיף, לגרור ולשנות את הסדר. כל חלק מקבל עיצוב משלו באתר.',
      type: 'array',
      of: sectionTypes.map((t) => defineArrayMember({ type: t.name })),
    }),
  ],
  preview: { select: { title: 'title', slug: 'slug.current' }, prepare: ({ title, slug }) => ({ title, subtitle: slug === 'home' ? '/' : `/${slug}` }) },
});

export const article = defineType({
  name: 'article',
  title: 'מאמר',
  type: 'document',
  icon: ComposeIcon,
  groups: [{ name: 'content', title: 'תוכן', default: true }, { name: 'seo', title: 'גוגל ושיתוף' }],
  fields: [
    defineField({ name: 'title', title: 'כותרת', type: 'string', group: 'content', validation: (r) => r.required() }),
    { ...slug(), group: 'content' },
    defineField({ name: 'excerpt', title: 'תקציר (מופיע בכרטיס "קראי עוד")', type: 'text', rows: 3, group: 'content', validation: (r) => r.required().max(260) }),
    defineField({ name: 'coverImage', title: 'תמונה ראשית', type: 'imageWithAlt', group: 'content' }),
    defineField({
      name: 'layout',
      title: 'עיצוב המאמר',
      type: 'string',
      group: 'content',
      description: 'שירי – שורות ממורכזות וטקסט גדול. קלאסי – פסקאות מיושרות לימין, נוח למאמר ארוך.',
      options: { list: [{ title: 'שירי', value: 'poetic' }, { title: 'קלאסי', value: 'classic' }], layout: 'radio', direction: 'horizontal' },
      initialValue: 'poetic',
    }),
    defineField({ name: 'tags', title: 'נושאים', type: 'array', of: [{ type: 'string' }], options: { layout: 'tags' }, group: 'content' }),
    defineField({ name: 'publishedAt', title: 'תאריך פרסום', type: 'date', group: 'content', initialValue: () => new Date().toISOString().slice(0, 10) }),
    defineField({ name: 'body', title: 'תוכן המאמר', type: 'richText', group: 'content' }),
    ...seoFields,
  ],
  orderings: [{ title: 'חדש קודם', name: 'newest', by: [{ field: 'publishedAt', direction: 'desc' }] }],
  preview: { select: { title: 'title', date: 'publishedAt', media: 'coverImage' }, prepare: ({ title, date, media }) => ({ title, subtitle: date, media }) },
});

export const recipe = defineType({
  name: 'recipe',
  title: 'מתכון',
  type: 'document',
  icon: LemonIcon,
  fields: [
    defineField({ name: 'title', title: 'שם המתכון', type: 'string', validation: (r) => r.required() }),
    slug(),
    defineField({ name: 'image', title: 'תמונה', type: 'imageWithAlt' }),
    defineField({ name: 'intro', title: 'כמה מילים על המתכון', type: 'richText' }),
    defineField({ name: 'spices', title: 'התבלינים במתכון', type: 'array', of: [defineArrayMember({ type: 'reference', to: [{ type: 'spice' }] })] }),
    defineField({ name: 'tags', title: 'תגיות', type: 'array', of: [{ type: 'string' }], options: { layout: 'tags' }, description: 'למשל: ללא גלוטן, טבעוני, מתוקים' }),
    defineField({
      name: 'ingredients',
      title: 'רכיבים',
      type: 'array',
      of: [{ type: 'string' }],
      description: 'שורה לכל רכיב. שורה שמסתיימת בנקודתיים (למשל "יבשים:") מוצגת ככותרת של קבוצת רכיבים.',
    }),
    defineField({
      name: 'steps',
      title: 'אופן ההכנה',
      description: 'בכל שלב אפשר לבחור את הרכיבים שנכנסים בו – כמו בצורת ההגשה של שנינה',
      type: 'array',
      of: [
        defineArrayMember({
          type: 'object',
          name: 'recipeStep',
          fields: [
            defineField({ name: 'heading', title: 'כותרת לפני השלב (לא חובה)', type: 'string', description: 'למשל "הרכבת הסושי" או "המשך לפיצה"' }),
            defineField({ name: 'ingredients', title: 'רכיבים לשלב הזה', type: 'array', of: [{ type: 'string' }], options: { layout: 'tags' } }),
            defineField({ name: 'text', title: 'הוראה', type: 'text', rows: 3, validation: (r) => r.required() }),
          ],
          preview: { select: { title: 'text', ing: 'ingredients' }, prepare: ({ title, ing }) => ({ title, subtitle: (ing ?? []).join(' · ') }) },
        }),
      ],
    }),
    defineField({ name: 'tips', title: 'טיפים', type: 'array', of: [{ type: 'text', rows: 2 }] }),
    defineField({ name: 'outro', title: 'לסיום – מילים על המתכון', type: 'richText', description: 'מופיע אחרי ההכנה והטיפים: על התבלין, על הבריאות, "בתאבון"...' }),
    defineField({ name: 'publishedAt', title: 'תאריך פרסום', type: 'date', initialValue: () => new Date().toISOString().slice(0, 10) }),
  ],
  orderings: [{ title: 'חדש קודם', name: 'newest', by: [{ field: 'publishedAt', direction: 'desc' }] }],
  preview: { select: { title: 'title', media: 'image', s0: 'spices.0.name' }, prepare: ({ title, media, s0 }) => ({ title, subtitle: s0 ? `תבלין: ${s0}` : undefined, media }) },
});

export const spice = defineType({
  name: 'spice',
  title: 'תבלין',
  type: 'document',
  icon: SparklesIcon,
  fields: [
    defineField({ name: 'name', title: 'שם התבלין', type: 'string', validation: (r) => r.required() }),
    slug('name'),
    defineField({ name: 'image', title: 'תמונה', type: 'imageWithAlt' }),
    defineField({ name: 'intro', title: 'תיאור קצר', type: 'richText' }),
    defineField({ name: 'properties', title: 'תכונות', type: 'array', of: [{ type: 'string' }], options: { layout: 'tags' } }),
    defineField({ name: 'facts', title: 'עובדות קטנות', type: 'array', of: [{ type: 'string' }] }),
    defineField({ name: 'body', title: 'הרחבה', type: 'richText' }),
  ],
  preview: { select: { title: 'name', media: 'image' } },
});

export const event = defineType({
  name: 'event',
  title: 'אירוע',
  type: 'document',
  icon: CalendarIcon,
  fields: [
    defineField({ name: 'title', title: 'שם האירוע', type: 'string', validation: (r) => r.required() }),
    defineField({
      name: 'kind',
      title: 'סוג',
      type: 'string',
      options: { list: [
        { title: 'מדיטציה', value: 'meditation' }, { title: 'הרצאה', value: 'lecture' }, { title: 'סדנה', value: 'workshop' },
        { title: 'הכשרה', value: 'training' }, { title: 'אחר', value: 'other' },
      ] },
      initialValue: 'meditation',
    }),
    defineField({ name: 'start', title: 'מתי מתחיל', type: 'datetime', validation: (r) => r.required() }),
    defineField({ name: 'end', title: 'מתי נגמר', type: 'datetime', description: 'אחרי מועד זה האירוע יורד מהאתר אוטומטית' }),
    defineField({ name: 'location', title: 'מיקום', type: 'string', description: 'למשל: זום, או כתובת' }),
    defineField({ name: 'isOnline', title: 'אונליין', type: 'boolean', initialValue: false }),
    defineField({ name: 'price', title: 'מחיר', type: 'string', description: 'למשל: 70 ש"ח' }),
    defineField({ name: 'description', title: 'תיאור', type: 'simpleText' }),
    defineField({ name: 'registrationUrl', title: 'קישור להרשמה', type: 'url' }),
    defineField({ name: 'image', title: 'תמונה', type: 'imageWithAlt' }),
  ],
  orderings: [{ title: 'לפי תאריך', name: 'start', by: [{ field: 'start', direction: 'asc' }] }],
  preview: {
    select: { title: 'title', start: 'start', media: 'image' },
    prepare: ({ title, start, media }) => ({ title, subtitle: start ? new Date(start).toLocaleString('he-IL', { dateStyle: 'medium', timeStyle: 'short' }) : '', media }),
  },
});

export const product = defineType({
  name: 'product',
  title: 'מרקחת',
  type: 'document',
  icon: PackageIcon,
  description: 'מוצר ב"המרקחות של שנינה". בגלריה רואים שם, תמונה, תת-כותרת ונפח/מחיר; הרכיבים, ההתוויות והאזהרות נפתחים במעבר עכבר או בלחיצה.',
  fields: [
    defineField({ name: 'title', title: 'שם המוצר', type: 'string', validation: (r) => r.required() }),
    slug('title'),
    defineField({ name: 'tagline', title: 'תת-כותרת', type: 'string' }),
    defineField({ name: 'image', title: 'תמונה', type: 'imageWithAlt' }),
    defineField({
      name: 'sizes', title: 'נפח ומחיר', type: 'array',
      description: 'שורה לכל גודל. המחיר אופציונלי – אפשר להשאיר ריק.',
      of: [defineArrayMember({
        name: 'productSize', type: 'object', title: 'גודל',
        fields: [
          defineField({ name: 'size', title: 'נפח / משקל', type: 'string', description: 'למשל: 10 מ"ל' }),
          defineField({ name: 'price', title: 'מחיר', type: 'string', description: 'למשל: 78 ₪' }),
        ],
        preview: { select: { title: 'size', subtitle: 'price' } },
      })],
    }),
    defineField({ name: 'usage', title: 'אופן השימוש', type: 'text', rows: 2 }),
    defineField({
      name: 'ingredients', title: 'רכיבים', type: 'text', rows: 4,
      description: 'מופרדים בפסיקים. למוצר עם כמה סוגים: שורה לכל סוג, בפורמט "שם הסוג: רכיב, רכיב".',
    }),
    defineField({ name: 'benefits', title: 'עשוי לעזור ל…', type: 'text', rows: 4, description: 'אפשר שורה לכל סוג, בפורמט "שם הסוג: טקסט".' }),
    defineField({ name: 'warnings', title: 'אזהרות', type: 'text', rows: 3 }),
    defineField({ name: 'note', title: 'הערה', type: 'text', rows: 2 }),
    defineField({ name: 'order', title: 'מיקום בגלריה', type: 'number', description: 'מספר קטן מופיע ראשון' }),
    defineField({ name: 'available', title: 'להציג באתר', type: 'boolean', initialValue: true }),
  ],
  orderings: [{ title: 'לפי מיקום', name: 'order', by: [{ field: 'order', direction: 'asc' }] }],
  preview: { select: { title: 'title', subtitle: 'tagline', media: 'image' } },
});

export const documentTypes = [siteSettings, page, article, recipe, spice, event, product];
