All files / src/viewmodels/event useCreateEventViewModel.ts

9% Statements 48/533
100% Branches 0/0
0% Functions 0/5
9% Lines 48/533

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 6691x 1x             1x 1x                   1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x               1x                         1x                                                                                                         1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                                                                                                                                                                                                                                                                                     1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        
import { useState, useCallback, useEffect, useRef } from 'react';
import {
  createEvent,
  listCategories,
  searchLocation,
  getEventImageUploadUrl,
  confirmEventImageUpload,
} from '@/services/eventService';
import { prepareAvatarBlobs } from '@/utils/imageResize';
import { uploadImageVariants } from '@/utils/directImageUpload';
import {
  CreateEventResponse,
  CategoryItem,
  LocationSuggestion,
  type PrivacyLevel,
  type PreferredGender,
  type EventConstraint,
  type LocationType,
} from '@/models/event';
import { ApiError } from '@/services/api';
import i18n from '@/i18n';
 
const TITLE_MIN = 10;
const TITLE_MAX = 60;
const DESC_MIN = 20;
const DESC_MAX = 600;
const CAPACITY_MIN = 2;
const MAX_TAGS = 5;
const TAG_MAX_LENGTH = 20;
export const MAX_CONSTRAINTS = 5;
export const ROUTE_MIN_POINTS = 2;
export const ROUTE_MAX_POINTS = 50;
 
export interface RouteWaypoint {
  lat: number;
  lon: number;
  label?: string | null;
}
 
export function deriveRouteAddress(waypoints: RouteWaypoint[]): string {
  if (waypoints.length === 0) return '';
  const shortLabel = (w: RouteWaypoint): string => {
    const trimmed = (w.label ?? '').split(',')[0]?.trim();
    if (trimmed) return trimmed;
    return `${w.lat.toFixed(4)}, ${w.lon.toFixed(4)}`;
  };
  const first = shortLabel(waypoints[0]);
  const last = shortLabel(waypoints[waypoints.length - 1]);
  if (waypoints.length === 1 || first === last) return first;
  return `${first} → ${last}`;
}
 
export const PRIVACY_LEVELS: PrivacyLevel[] = ['PUBLIC', 'PROTECTED', 'PRIVATE'];
 
export type ConstraintType = 'gender' | 'age' | 'capacity' | 'other';
 
export interface CreateEventFormData {
  title: string;
  description: string;
  /** Local file to upload via presigned URLs after the event is created. */
  imageFile: File | null;
  imagePreview: string;
  categoryId: number | null;
  locationType: LocationType;
  locationQuery: string;
  address: string;
  lat: number | null;
  lon: number | null;
  routePoints: RouteWaypoint[];
  startDate: string;
  startTime: string;
  endDate: string;
  endTime: string;
  privacyLevel: PrivacyLevel;
  tags: string[];
  tagInput: string;
  capacity: string;
  minimumAge: string;
  maximumAge: string;
  preferredGender: PreferredGender | '';
  childFriendly: boolean;
  familyOriented: boolean;
  constraints: EventConstraint[];
  constraintType: ConstraintType;
  otherConstraintInput: string;
}
 
export interface CreateEventFormErrors {
  image?: string | null;
  title?: string | null;
  description?: string | null;
  categoryId?: string | null;
  location?: string | null;
  startDate?: string | null;
  startTime?: string | null;
  endDate?: string | null;
  endTime?: string | null;
  tags?: string | null;
  capacity?: string | null;
  minimumAge?: string | null;
  maximumAge?: string | null;
}
 
type CreateEventTouchedFields = Partial<Record<keyof CreateEventFormErrors, boolean>>;
 
const INITIAL: CreateEventFormData = {
  title: '',
  description: '',
  imageFile: null,
  imagePreview: '',
  categoryId: null,
  locationType: 'POINT',
  locationQuery: '',
  address: '',
  lat: null,
  lon: null,
  routePoints: [],
  startDate: '',
  startTime: '',
  endDate: '',
  endTime: '',
  privacyLevel: 'PUBLIC',
  tags: [],
  tagInput: '',
  capacity: '',
  minimumAge: '',
  maximumAge: '',
  preferredGender: '',
  childFriendly: false,
  familyOriented: false,
  constraints: [],
  constraintType: 'other',
  otherConstraintInput: '',
};
 
function toISODateTime(date: string, time: string): string | null {
  if (!date || !time) return null;
  try {
    const dt = new Date(`${date}T${time}`);
    if (isNaN(dt.getTime())) return null;
    return dt.toISOString();
  } catch {
    return null;
  }
}
 
function toDateOnly(date: string): Date | null {
  if (!date) return null;
  const dt = new Date(`${date}T00:00:00`);
  return Number.isNaN(dt.getTime()) ? null : dt;
}
 
function validateForm(form: CreateEventFormData): CreateEventFormErrors {
  const errors: CreateEventFormErrors = {};
 
  if (!form.title.trim()) {
    errors.title = i18n.t('errors.create_event_title_required');
  } else if (form.title.trim().length < TITLE_MIN) {
    errors.title = i18n.t('errors.create_event_title_min', { count: TITLE_MIN });
  } else if (form.title.trim().length > TITLE_MAX) {
    errors.title = i18n.t('errors.create_event_title_max', { count: TITLE_MAX });
  }
 
  if (!form.description.trim()) {
    errors.description = i18n.t('errors.create_event_description_required');
  } else if (form.description.trim().length < DESC_MIN) {
    errors.description = i18n.t('errors.create_event_description_min', { count: DESC_MIN });
  } else if (form.description.trim().length > DESC_MAX) {
    errors.description = i18n.t('errors.create_event_description_max', { count: DESC_MAX });
  }
 
  if (!form.categoryId) {
    errors.categoryId = i18n.t('errors.create_event_category_required');
  }
 
  if (!form.imageFile) {
    errors.image = i18n.t('errors.create_event_image_required');
  }
 
  if (form.locationType === 'ROUTE') {
    if (form.routePoints.length < ROUTE_MIN_POINTS) {
      errors.location = i18n.t('errors.create_event_route_min_points', { count: ROUTE_MIN_POINTS });
    }
  } else if (form.lat === null || form.lon === null) {
    errors.location = i18n.t('errors.create_event_location_required');
  }
 
  if (!form.startDate) {
    errors.startDate = i18n.t('errors.create_event_start_date_required');
  }
  if (!form.startTime) {
    errors.startTime = i18n.t('errors.create_event_start_time_required');
  }
 
  const now = new Date();
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
 
  const startDateOnly = form.startDate ? toDateOnly(form.startDate) : null;
  if (form.startDate && !startDateOnly) {
    errors.startDate = i18n.t('errors.create_event_start_date_invalid');
  } else if (startDateOnly && startDateOnly < today) {
    errors.startDate = i18n.t('errors.create_event_start_date_past');
  }
 
  const startISO = !errors.startDate && form.startDate && form.startTime
    ? toISODateTime(form.startDate, form.startTime)
    : null;
 
  if (!errors.startDate && form.startDate && form.startTime && !startISO) {
    errors.startTime = i18n.t('errors.create_event_start_time_invalid');
  } else if (
    !errors.startDate
    && startDateOnly
    && startDateOnly.getTime() === today.getTime()
    && startISO
    && new Date(startISO) <= now
  ) {
    errors.startTime = i18n.t('errors.create_event_start_time_future');
  }
 
  if (form.endDate || form.endTime) {
    if (!form.endDate) errors.endDate = i18n.t('errors.create_event_end_date_required');
    if (!form.endTime) errors.endTime = i18n.t('errors.create_event_end_time_required');
 
    const endDateOnly = form.endDate ? toDateOnly(form.endDate) : null;
    if (form.endDate && !endDateOnly) {
      errors.endDate = i18n.t('errors.create_event_end_date_invalid');
    } else if (!errors.startDate && startDateOnly && endDateOnly && endDateOnly < startDateOnly) {
      errors.endDate = i18n.t('errors.create_event_end_date_before_start');
    }
 
    const endISO = !errors.endDate && form.endDate && form.endTime
      ? toISODateTime(form.endDate, form.endTime)
      : null;
 
    if (!errors.endDate && form.endDate && form.endTime && !endISO) {
      errors.endTime = i18n.t('errors.create_event_end_time_invalid');
    } else if (
      !errors.endDate
      && !errors.startDate
      && startDateOnly
      && endDateOnly
      && startISO
      && endISO
      && endDateOnly.getTime() === startDateOnly.getTime()
      && new Date(endISO) <= new Date(startISO)
    ) {
      errors.endTime = i18n.t('errors.create_event_end_time_before_start');
    }
  }
 
  if (form.capacity) {
    const cap = parseInt(form.capacity, 10);
    if (isNaN(cap) || cap < CAPACITY_MIN) {
      errors.capacity = i18n.t('errors.create_event_capacity_min', { count: CAPACITY_MIN });
    }
  }
 
  if (form.minimumAge) {
    const age = parseInt(form.minimumAge, 10);
    if (isNaN(age) || age < 1 || age > 120) {
      errors.minimumAge = i18n.t('errors.create_event_age_invalid');
    }
  }
 
  if (form.maximumAge) {
    const age = parseInt(form.maximumAge, 10);
    if (isNaN(age) || age < 1 || age > 120) {
      errors.maximumAge = i18n.t('errors.create_event_age_invalid');
    } else if (form.minimumAge) {
      const minAge = parseInt(form.minimumAge, 10);
      if (!isNaN(minAge) && age <= minAge) {
        errors.maximumAge = i18n.t('errors.create_event_max_age_gt_min');
      }
    }
  }
 
  return errors;
}
 
export function useCreateEventViewModel() {
  const [form, setForm] = useState<CreateEventFormData>(INITIAL);
  const [errors, setErrors] = useState<CreateEventFormErrors>({});
  const [touched, setTouched] = useState<CreateEventTouchedFields>({});
  const [submitAttempted, setSubmitAttempted] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [isUploadingImage, setIsUploadingImage] = useState(false);
  const [apiError, setApiError] = useState<string | null>(null);
  const [imageError, setImageError] = useState<string | null>(null);
  const [imageUploadSuccessMessage, setImageUploadSuccessMessage] = useState<string | null>(null);
  const [coverImageUploadedForLastCreate, setCoverImageUploadedForLastCreate] = useState(false);
  const [successMessage, setSuccessMessage] = useState<string | null>(null);
  const [categories, setCategories] = useState<CategoryItem[]>([]);
  const [locationResults, setLocationResults] = useState<LocationSuggestion[]>([]);
  const [locationSearching, setLocationSearching] = useState(false);
  const searchTimeout = useRef<ReturnType<typeof setTimeout>>(undefined);
  const imageUploadSuccessTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
 
  const clearImageUploadSuccessToast = useCallback(() => {
    if (imageUploadSuccessTimerRef.current) {
      clearTimeout(imageUploadSuccessTimerRef.current);
      imageUploadSuccessTimerRef.current = null;
    }
    setImageUploadSuccessMessage(null);
  }, []);
 
  useEffect(
    () => () => {
      if (imageUploadSuccessTimerRef.current) clearTimeout(imageUploadSuccessTimerRef.current);
    },
    [],
  );
 
  useEffect(() => {
    listCategories()
      .then((res) => setCategories(res.items))
      .catch(() => {});
  }, []);
 
  const getVisibleErrors = useCallback(
    (nextForm: CreateEventFormData, nextTouched: CreateEventTouchedFields, forceAll = false) => {
      const validationErrors = validateForm(nextForm);
      if (forceAll) return validationErrors;
 
      const visibleErrors: CreateEventFormErrors = {};
      (Object.keys(validationErrors) as (keyof CreateEventFormErrors)[]).forEach((key) => {
        if (nextTouched[key]) {
          visibleErrors[key] = validationErrors[key];
        }
      });
      return visibleErrors;
    },
    [],
  );
 
  useEffect(() => {
    setErrors(getVisibleErrors(form, touched, submitAttempted));
  }, [form, touched, submitAttempted, getVisibleErrors]);
 
  const updateField = useCallback(
    <K extends keyof CreateEventFormData>(field: K, value: CreateEventFormData[K]) => {
      setForm((prev) => ({ ...prev, [field]: value }));
      setApiError(null);
      setImageError(null);
      setSuccessMessage(null);
      clearImageUploadSuccessToast();
      setCoverImageUploadedForLastCreate(false);
    },
    [clearImageUploadSuccessToast],
  );
 
  const touchField = useCallback(
    (field: keyof CreateEventFormErrors) => {
      setTouched((prev) => {
        if (prev[field]) return prev;
        return { ...prev, [field]: true };
      });
    },
    [],
  );
 
  const handleLocationSearch = useCallback((query: string) => {
    updateField('locationQuery', query);
    updateField('lat', null);
    updateField('lon', null);
    updateField('address', '');
    setLocationResults([]);
 
    if (searchTimeout.current) clearTimeout(searchTimeout.current);
    if (query.trim().length < 3) return;
 
    searchTimeout.current = setTimeout(async () => {
      setLocationSearching(true);
      try {
        const results = await searchLocation(query);
        setLocationResults(results);
      } catch {
        setLocationResults([]);
      } finally {
        setLocationSearching(false);
      }
    }, 400);
  }, [updateField]);
 
  const selectLocation = useCallback((suggestion: LocationSuggestion) => {
    setForm((prev) => ({
      ...prev,
      locationQuery: suggestion.display_name,
      address: suggestion.display_name,
      lat: parseFloat(suggestion.lat),
      lon: parseFloat(suggestion.lon),
    }));
    setLocationResults([]);
    setErrors((prev) => ({ ...prev, location: undefined }));
  }, []);
 
  const addTag = useCallback(() => {
    setForm((prev) => {
      const tag = prev.tagInput.trim();
      if (!tag || prev.tags.length >= MAX_TAGS || tag.length > TAG_MAX_LENGTH) return prev;
      if (prev.tags.some((t) => t.toLowerCase() === tag.toLowerCase())) return prev;
      return { ...prev, tags: [...prev.tags, tag], tagInput: '' };
    });
  }, []);
 
  const removeTag = useCallback((index: number) => {
    setForm((prev) => ({
      ...prev,
      tags: prev.tags.filter((_, i) => i !== index),
    }));
  }, []);
 
  const addConstraint = useCallback(() => {
    setForm((prev) => {
      if (prev.constraints.length >= MAX_CONSTRAINTS) return prev;
      let constraint: EventConstraint | null = null;
 
      if (prev.constraintType === 'other' && prev.otherConstraintInput.trim()) {
        constraint = { type: 'other', info: prev.otherConstraintInput.trim() };
      }
 
      if (!constraint) return prev;
      return {
        ...prev,
        constraints: [...prev.constraints, constraint],
        otherConstraintInput: '',
      };
    });
  }, []);
 
  const handleImageUpload = useCallback(
    (file: File | null) => {
      setImageError(null);
      setTouched((prev) => ({ ...prev, image: true }));
      
      if (!file) {
        setForm((prev) => ({ ...prev, imageFile: null, imagePreview: '' }));
        return;
      }
      
      const reader = new FileReader();
      reader.onloadend = () => {
        setForm((prev) => ({ ...prev, imageFile: file, imagePreview: reader.result as string }));
      };
      reader.readAsDataURL(file);
    },
    [],
  );
 
  const removeImage = useCallback(() => {
    setImageError(null);
    setTouched((prev) => ({ ...prev, image: true }));
    setForm((prev) => ({ ...prev, imageFile: null, imagePreview: '' }));
  }, []);
 
  const setLocationType = useCallback((type: LocationType) => {
    setForm((prev) => {
      if (prev.locationType === type) return prev;
      return {
        ...prev,
        locationType: type,
        ...(type === 'ROUTE'
          ? { lat: null, lon: null, address: '', locationQuery: '' }
          : { routePoints: [] }),
      };
    });
    setLocationResults([]);
    setErrors((prev) => ({ ...prev, location: undefined }));
  }, []);
 
  const addRoutePointFromSuggestion = useCallback((suggestion: LocationSuggestion) => {
    const lat = parseFloat(suggestion.lat);
    const lon = parseFloat(suggestion.lon);
    if (Number.isNaN(lat) || Number.isNaN(lon)) return;
    setForm((prev) => {
      if (prev.routePoints.length >= ROUTE_MAX_POINTS) return prev;
      return {
        ...prev,
        locationQuery: '',
        routePoints: [
          ...prev.routePoints,
          { lat, lon, label: suggestion.display_name },
        ],
      };
    });
    setLocationResults([]);
    setErrors((prev) => ({ ...prev, location: undefined }));
  }, []);
 
  const addRoutePointFromCoordinate = useCallback(
    (lat: number, lon: number, label?: string | null) => {
      setForm((prev) => {
        if (prev.routePoints.length >= ROUTE_MAX_POINTS) return prev;
        return {
          ...prev,
          routePoints: [...prev.routePoints, { lat, lon, label: label ?? null }],
        };
      });
      setErrors((prev) => ({ ...prev, location: undefined }));
    },
    [],
  );
 
  const removeRoutePoint = useCallback((index: number) => {
    setForm((prev) => {
      if (index < 0 || index >= prev.routePoints.length) return prev;
      const next = [...prev.routePoints];
      next.splice(index, 1);
      return { ...prev, routePoints: next };
    });
  }, []);
 
  const moveRoutePoint = useCallback((index: number, direction: -1 | 1) => {
    setForm((prev) => {
      const target = index + direction;
      if (target < 0 || target >= prev.routePoints.length) return prev;
      const next = [...prev.routePoints];
      [next[index], next[target]] = [next[target], next[index]];
      return { ...prev, routePoints: next };
    });
  }, []);
 
  const updateRoutePointLabel = useCallback((index: number, label: string) => {
    setForm((prev) => {
      if (index < 0 || index >= prev.routePoints.length) return prev;
      const next = [...prev.routePoints];
      next[index] = { ...next[index], label };
      return { ...prev, routePoints: next };
    });
  }, []);
 
  const removeConstraint = useCallback((index: number) => {
    setForm((prev) => ({
      ...prev,
      constraints: prev.constraints.filter((_, i) => i !== index),
    }));
  }, []);
 
  const handleSubmit = useCallback(
    async (token: string): Promise<CreateEventResponse | null> => {
      setSubmitAttempted(true);
      const validationErrors = validateForm(form);
      const hasErrors = Object.values(validationErrors).some((e) => e != null);
      if (hasErrors) {
        // Errors will be synced by the useEffect, but we can set them immediately too for responsiveness
        setErrors(validationErrors);
        return null;
      }
 
      setIsLoading(true);
      setApiError(null);
      setImageError(null);
      clearImageUploadSuccessToast();
      setCoverImageUploadedForLastCreate(false);
      try {
        const startTime = toISODateTime(form.startDate, form.startTime)!;
        const endTime = toISODateTime(form.endDate, form.endTime);
 
        const isRoute = form.locationType === 'ROUTE';
        const routeAddress = isRoute ? deriveRouteAddress(form.routePoints) : undefined;
 
        const request = {
          title: form.title.trim(),
          description: form.description.trim(),
          category_id: form.categoryId!,
          address: isRoute ? routeAddress : (form.address || undefined),
          ...(isRoute
            ? { route_points: form.routePoints.map((p) => ({ lat: p.lat, lon: p.lon })) }
            : { lat: form.lat!, lon: form.lon! }),
          location_type: form.locationType,
          start_time: startTime,
          end_time: endTime || undefined,
          capacity: form.capacity ? parseInt(form.capacity, 10) : undefined,
          privacy_level: form.privacyLevel,
          tags: form.tags.length > 0 ? form.tags : undefined,
          constraints: form.constraints.length > 0 ? form.constraints : undefined,
          minimum_age: form.minimumAge ? parseInt(form.minimumAge, 10) : undefined,
          maximum_age: form.maximumAge ? parseInt(form.maximumAge, 10) : undefined,
          preferred_gender: form.preferredGender || undefined,
          child_friendly: form.childFriendly,
          family_oriented: form.familyOriented,
        };
 
        const result = await createEvent(request, token);
 
        if (form.imageFile) {
          setIsUploadingImage(true);
          setImageError(null);
          try {
            const { original, small } = await prepareAvatarBlobs(form.imageFile);
            const uploadInit = await getEventImageUploadUrl(result.id, token);
            await uploadImageVariants(uploadInit, { original, small });
            await confirmEventImageUpload(
              result.id,
              { confirm_token: uploadInit.confirm_token },
              token,
            );
            setCoverImageUploadedForLastCreate(true);
            if (imageUploadSuccessTimerRef.current) clearTimeout(imageUploadSuccessTimerRef.current);
            setImageUploadSuccessMessage(i18n.t('create_event.cover_uploaded_message'));
            imageUploadSuccessTimerRef.current = setTimeout(() => {
              setImageUploadSuccessMessage(null);
              imageUploadSuccessTimerRef.current = null;
            }, 5000);
          } catch (err) {
            if (err instanceof ApiError) {
              setImageError(err.message);
            } else {
              setImageError(
                err instanceof Error
                  ? err.message
                  : i18n.t('errors.create_event_image_upload_failed_after_create'),
              );
            }
          } finally {
            setIsUploadingImage(false);
          }
        }
 
        setSuccessMessage(i18n.t('errors.create_event_created_success'));
        return result;
      } catch (err) {
        if (err instanceof ApiError) {
          setApiError(err.message);
        } else {
          setApiError(i18n.t('errors.unexpected'));
        }
        return null;
      } finally {
        setIsLoading(false);
      }
    },
    [form, clearImageUploadSuccessToast],
  );
 
  return {
    form,
    errors,
    isLoading,
    isUploadingImage,
    apiError,
    imageError,
    imageUploadSuccessMessage,
    coverImageUploadedForLastCreate,
    dismissImageUploadSuccess: clearImageUploadSuccessToast,
    successMessage,
    categories,
    locationResults,
    locationSearching,
    touchField,
    updateField,
    handleLocationSearch,
    selectLocation,
    setLocationType,
    addRoutePointFromSuggestion,
    addRoutePointFromCoordinate,
    removeRoutePoint,
    moveRoutePoint,
    updateRoutePointLabel,
    addTag,
    removeTag,
    handleImageUpload,
    removeImage,
    addConstraint,
    removeConstraint,
    handleSubmit,
  };
}