import z from 'zod';

import {
  MAX_CUSTOM_LOCATION_LENGTH,
  // MIN_CREATOR_QUERY_LENGTH,
  MAX_DESC_LENGTH,
  MAX_TITLE_LENGTH,
} from '@/lib/constants/eventSubmitFormContants';

export type EventFormValues = z.infer<typeof eventSubmitFormSchema>;

export const eventSubmitFormSchema = z
  .object({
    startDate: z.string().min(1, 'A kezdő dátum megadása kötelező'),
    startTime: z.string().optional(),
    endDate: z.string().optional(),
    endTime: z.string().optional(),
    eventName: z
      .string()
      .min(1, 'Az esemény címének megadása kötelező')
      .max(MAX_TITLE_LENGTH, `Az esemény címe maximum ${MAX_TITLE_LENGTH} karakter lehet`),
    description: z
      .string()
      .max(MAX_DESC_LENGTH, `A leírás maximum ${MAX_DESC_LENGTH} karakter lehet`)
      .optional(),
    infoUrl: z.string().url('Helytelen URL formátum').optional().or(z.literal('')),
    ticketUrl: z.string().url('Helytelen URL formátum').optional().or(z.literal('')),
    customLocation: z
      .string()
      .max(
        MAX_CUSTOM_LOCATION_LENGTH,
        `A helyszín maximum ${MAX_CUSTOM_LOCATION_LENGTH} karakter lehet`
      )
      .optional(),
    notes: z.string().max(2000, 'Az üzenet maximum 2000 karakter hosszú lehet').optional(),
    useCustomLocation: z.boolean(),
    isMultiDay: z.boolean().optional(),
    selectedInstitution: z.number().optional(),
    eventCategory: z.number().optional(),
    customRadioInput: z.string().optional(),
    selectedCategory: z.number().optional(),
    selectedType: z.number().optional(),
    selectedSubtype: z.number().optional(),
    selectedCreators: z.array(z.number()).min(1, 'Legalább egy alkotó megadása kötelező'),
    selectedCreatorsObjects: z.array(z.any()).optional(), // Store creator objects for display
    otherCreators: z.string().max(200, 'Maximum 200 karakter hosszú lehet').optional(),
    uploadedImages: z.array(z.string()).max(2).optional(),
  })
  .superRefine((data, ctx) => {
    // Either institution is selected OR custom location has text
    const hasInstitution =
      data.selectedInstitution !== undefined && data.selectedInstitution !== null;
    const hasCustomLocation = data.customLocation && data.customLocation.trim().length > 0;

    if (!hasInstitution && !hasCustomLocation) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        message: 'Intézmény vagy egyéni helyszín megadása kötelező',
        path: ['selectedInstitution'],
      });
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        message: 'Intézmény vagy egyéni helyszín megadása kötelező',
        path: ['customLocation'],
      });
    }

    // Category is required
    if (data.eventCategory === undefined || data.eventCategory === null) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        message: 'A kategória megadása kötelező',
        path: ['eventCategory'],
      });
    }
  });
