import type { CollectionConfig } from 'payload'
import { authenticated } from '../access/authenticated'
import { authenticatedOrPublished } from '../access/authenticatedOrPublished'
import { slugField } from 'payload'
import { populatePublishedAt } from '../hooks/populatePublishedAt'
import { generatePreviewPath } from '../utilities/generatePreviewPath'

import {
  MetaDescriptionField,
  MetaImageField,
  MetaTitleField,
  OverviewField,
  PreviewField,
} from '@payloadcms/plugin-seo/fields'

export const Projects: CollectionConfig = {
  slug: 'projects',
  labels: {
    singular: 'Project',
    plural: 'Projects',
  },
  access: {
    create: authenticated,
    delete: authenticated,
    read: authenticatedOrPublished,
    update: authenticated,
  },
  defaultPopulate: {
    name: true,
    slug: true,
    categories: true,
    meta: {
      image: true,
      description: true,
    },
  },
  admin: {
    useAsTitle: 'name',
    defaultColumns: ['name', 'client', 'year', 'featured', 'updatedAt'],
    livePreview: {
      url: ({ data, req }) =>
        generatePreviewPath({
          slug: data?.slug,
          collection: 'projects',
          req,
        }),
    },
    preview: (data, { req }) =>
      generatePreviewPath({
        slug: data?.slug as string,
        collection: 'projects',
        req,
      }),
  },
  fields: [
    {
      name: 'name',
      type: 'text',
      required: true,
      localized: true,
    },
    {
      type: 'tabs',
      tabs: [
        {
          label: 'Content',
          fields: [
            {
              name: 'heroImage',
              type: 'upload',
              relationTo: 'media',
              required: true,
              admin: {
                description: 'Main project image/screenshot',
              },
            },
            {
              name: 'shortDescription',
              type: 'textarea',
              required: true,
              localized: true,
              admin: {
                description: 'Brief description for cards and previews (max 200 chars)',
              },
              validate: (val: string | null | undefined) => {
                if (val && val.length > 200) {
                  return 'Short description must be 200 characters or less'
                }
                return true
              },
            },
            {
              name: 'description',
              type: 'richText',
              required: true,
              localized: true,
              admin: {
                description: 'Full project description and details',
              },
            },
            {
              name: 'problem',
              type: 'richText',
              localized: true,
              admin: {
                description: 'Problem statement: What challenge did this project solve?',
              },
            },
            {
              name: 'solution',
              type: 'richText',
              localized: true,
              admin: {
                description: 'Solution: How did you solve it?',
              },
            },
            {
              name: 'results',
              type: 'richText',
              localized: true,
              admin: {
                description: 'Results: What were the outcomes?',
              },
            },
            {
              name: 'client',
              type: 'text',
              localized: true,
              admin: {
                description: 'Client name (optional, can anonymize if needed)',
              },
            },
            {
              name: 'year',
              type: 'number',
              admin: {
                description: 'Year of completion',
              },
            },
            {
              name: 'duration',
              type: 'text',
              localized: true,
              admin: {
                description: 'Project duration (e.g., "3 months", "6 weeks")',
              },
            },
            {
              name: 'role',
              type: 'text',
              localized: true,
              admin: {
                description: 'Your role in the project (e.g., "Lead Developer", "Full Stack Developer")',
              },
            },
            {
              name: 'teamSize',
              type: 'text',
              localized: true,
              admin: {
                description: 'Team size (e.g., "Solo project", "Team of 5")',
              },
            },
          ],
        },
        {
          label: 'Technical',
          fields: [
            {
              name: 'techStack',
              type: 'array',
              label: 'Tech Stack',
              required: true,
              fields: [
                {
                  name: 'name',
                  type: 'text',
                  required: true,
                  admin: {
                    description: 'Technology name (e.g., "React", "Node.js", "PostgreSQL")',
                  },
                },
                {
                  name: 'category',
                  type: 'select',
                  options: [
                    { label: 'Frontend', value: 'frontend' },
                    { label: 'Backend', value: 'backend' },
                    { label: 'Database', value: 'database' },
                    { label: 'DevOps', value: 'devops' },
                    { label: 'Tool', value: 'tool' },
                    { label: 'Other', value: 'other' },
                  ],
                },
              ],
              admin: {
                initCollapsed: true,
                components: {
                  RowLabel: '@/components/RowLabel#RowLabel',
                },
              },
            },
            {
              name: 'highlights',
              type: 'array',
              label: 'Technical Highlights',
              fields: [
                {
                  name: 'title',
                  type: 'text',
                  required: true,
                  localized: true,
                },
                {
                  name: 'description',
                  type: 'textarea',
                  required: true,
                  localized: true,
                },
              ],
              admin: {
                description: 'Key technical achievements or interesting challenges solved',
                initCollapsed: true,
                components: {
                  RowLabel: '@/components/RowLabel#RowLabel',
                },
              },
            },
          ],
        },
        {
          label: 'Media & Links',
          fields: [
            {
              name: 'gallery',
              type: 'array',
              fields: [
                {
                  name: 'image',
                  type: 'upload',
                  relationTo: 'media',
                  required: true,
                },
                {
                  name: 'caption',
                  type: 'text',
                  localized: true,
                },
                {
                  name: 'alt',
                  type: 'text',
                  required: true,
                  localized: true,
                },
              ],
              admin: {
                description: 'Additional screenshots, diagrams, or images',
              },
            },
            {
              name: 'liveUrl',
              type: 'text',
              admin: {
                description: 'Link to live project (if public)',
              },
            },
            {
              name: 'githubUrl',
              type: 'text',
              admin: {
                description: 'GitHub repository URL (if public)',
              },
            },
            {
              name: 'videoUrl',
              type: 'text',
              admin: {
                description: 'Project demo video URL (YouTube, Vimeo, etc.)',
              },
            },
            {
              name: 'caseStudyUrl',
              type: 'text',
              admin: {
                description: 'Link to external case study or blog post',
              },
            },
          ],
        },
        {
          label: 'Relationships',
          fields: [
            {
              name: 'categories',
              type: 'relationship',
              relationTo: 'categories',
              hasMany: true,
              required: true,
              filterOptions: {
                type: { equals: 'project' },
              },
              admin: {
                description: 'Project categories (can select multiple)',
              },
            },
            {
              name: 'relatedProjects',
              type: 'relationship',
              relationTo: 'projects',
              hasMany: true,
              filterOptions: ({ id }) => ({
                id: { not_in: [id] },
              }),
              admin: {
                description: 'Similar or related projects',
              },
            },
          ],
        },
        {
          name: 'meta',
          label: 'SEO',
          fields: [
            OverviewField({
              titlePath: 'meta.title',
              descriptionPath: 'meta.description',
              imagePath: 'meta.image',
            }),
            MetaTitleField({
              hasGenerateFn: true,
            }),
            MetaImageField({
              relationTo: 'media',
            }),
            MetaDescriptionField({}),
            PreviewField({
              hasGenerateFn: true,
              titlePath: 'meta.title',
              descriptionPath: 'meta.description',
            }),
          ],
        },
      ],
    },
    {
      name: 'featured',
      type: 'checkbox',
      defaultValue: false,
      admin: {
        position: 'sidebar',
        description: 'Display this project prominently on the homepage',
      },
    },
    {
      name: 'projectStatus',
      type: 'select',
      label: 'Project Status',
      required: true,
      defaultValue: 'completed',
      options: [
        { label: 'Completed', value: 'completed' },
        { label: 'In Progress', value: 'in-progress' },
        { label: 'Archived', value: 'archived' },
      ],
      admin: {
        position: 'sidebar',
      },
    },
    {
      name: 'publishedAt',
      type: 'date',
      admin: {
        position: 'sidebar',
        date: {
          pickerAppearance: 'dayAndTime',
        },
      },
      hooks: {
        beforeChange: [
          ({ siblingData, value }) => {
            if (siblingData._status === 'published' && !value) {
              return new Date()
            }
            return value
          },
        ],
      },
    },
    slugField(),
  ],
  hooks: {
    beforeChange: [populatePublishedAt],
  },
  versions: {
    drafts: {
      autosave: {
        interval: 100,
      },
      schedulePublish: true,
    },
    maxPerDoc: 50,
  },
}