All files / src/components/organizer/EventManagement EventForm.tsx

40.74% Statements 88/216
48.18% Branches 93/193
39.62% Functions 21/53
42.3% Lines 88/208

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 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012                                                                                                                                                                                2x 80x 80x 80x 80x 80x     80x 80x 80x   80x 80x     80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x     80x       80x 29x   20x 9x   9x           80x 29x 9x 9x   9x                                                                 6x         9x         80x   80x                                                                                         80x     80x 80x 80x   80x 29x           29x       80x             80x 29x 20x                               80x 29x 9x                               80x             80x 80x   80x 80x                 80x                                                                                       80x 1x   1x         1x     1x                                     1x                                         1x   1x 1x       80x                                                                                                                                                                                                                                       80x               80x 1x 1x     80x 1x     1x       80x         80x         80x                         80x                                                                                                                                             56x                               56x                                     56x                                                                               56x                                 56x                                         56x                             56x                                     56x                                                                                                                                                                           56x                             56x                                                                                                                                                                                                                                                  
/**
 * EventForm Component
 *
 * Modal form for creating and editing events
 * - Create and edit modes with pre-filled data
 * - Form validation (date 30+ days future, deadline 7+ days before event, capacity positive)
 * - Auto-save functionality (5-second debounce, always enabled, NOT configurable)
 * - Unsaved changes warning
 * - Draft save support for create mode
 * - Partial update support (PATCH for changed fields only)
 * - Role-based access control (organizer-only editing)
 *
 * Story: 2.5.3 - Event Management Frontend
 * Acceptance Criteria: AC3 (Create), AC4 (Edit), AC20 (Auto-Save)
 * Wireframe: docs/wireframes/story-1.16-event-detail-edit.md v1.1
 */
 
import React, { useEffect, useState, useCallback } from 'react';
import { useForm, Controller } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
  Button,
  Select,
  MenuItem,
  FormControl,
  InputLabel,
  FormHelperText,
  Alert,
  Box,
  Typography,
  Chip,
  Checkbox,
  FormControlLabel,
  Tabs,
  Tab,
  useMediaQuery,
  useTheme,
  IconButton,
  Tooltip,
  CircularProgress,
} from '@mui/material';
import { AutoAwesome } from '@mui/icons-material';
import { useTranslation } from 'react-i18next';
import { useAuth } from '@/hooks/useAuth';
import { useCreateEvent, useUpdateEvent } from '@/hooks/useEvents';
import { useAiGenerateDescription } from '@/hooks/useAiAssist';
import { useFeatureFlags } from '@/hooks/useFeatureFlags';
import { topicService } from '@/services/topicService';
import type { Topic } from '@/types/topic.types';
import type { Event, EventUI, CreateEventRequest } from '@/types/event.types';
import { useDebounce } from '@/hooks/useDebounce';
import { FileUpload } from '@/components/shared/FileUpload/FileUpload';
import { EventTypeSelector } from '@/components/organizer/EventTypeSelector/EventTypeSelector';
import type { components } from '@/types/generated/events-core-api.types';
import { workflowService } from '@/services/workflowService';
import { useQueryClient } from '@tanstack/react-query';
import { EventTasksTab } from '../Tasks/EventTasksTab';
import type { EventTaskResponse } from '@/services/taskService';
import { taskService } from '@/services/taskService';
import {
  createEventSchema,
  normalizeEventType,
  transformDatesForApi,
  getChangedFields as diffEventFields,
  type EventFormData,
  type PartialEventFormData,
} from './eventFormSchema';
 
// mapWorkflowStateToStatus function removed - no longer needed
// Backend now uses workflowState directly (Phase 1-2 migration complete)
//
// normalizeEventType, createEventSchema, EventFormData, PartialEventFormData,
// transformDatesForApi and getChangedFields now live in ./eventFormSchema
// (shared with the Details · Info in-tab editor — Story 14.F.2).
 
interface EventFormProps {
  open: boolean;
  mode: 'create' | 'edit';
  event?: Event;
  onClose: () => void;
  onSuccess?: (updatedEvent?: Event) => void;
}
 
export const EventForm: React.FC<EventFormProps> = ({ open, mode, event, onClose, onSuccess }) => {
  const { t } = useTranslation('events');
  const { t: tOrg } = useTranslation('organizer');
  const { user, isLoading: isAuthLoading } = useAuth();
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down('md'));
 
  // Mutation hooks for proper cache management (MVC pattern)
  const createEventMutation = useCreateEvent();
  const updateEventMutation = useUpdateEvent();
  const queryClient = useQueryClient();
 
  const [apiError, setApiError] = useState<string | null>(null);
  const [autoSaveStatus, setAutoSaveStatus] = useState<'idle' | 'saving' | 'saved' | 'error'>(
    'idle'
  );
  const [lastSavedAt, setLastSavedAt] = useState<Date | null>(null);
  const [showUnsavedWarning, setShowUnsavedWarning] = useState(false);
  const [initialFormData, setInitialFormData] = useState<PartialEventFormData>({});
  const [themeImageUploadId, setThemeImageUploadId] = useState<string | undefined>(undefined);
  const [overrideValidation, setOverrideValidation] = useState(false);
  const [overrideReason, setOverrideReason] = useState('');
  const [currentTab, setCurrentTab] = useState(0);
  const [selectedTemplates, setSelectedTemplates] = useState<string[]>([]);
  const [disabledTemplates, setDisabledTemplates] = useState<string[]>([]); // Templates with task instances
  const [templateAssignees, setTemplateAssignees] = useState<Record<string, string>>({});
  const [customTasks, setCustomTasks] = useState<EventTaskResponse[]>([]);
 
  // Check role-based access control
  const hasEditPermission = user?.role === 'organizer';
 
  // Initialize themeImageUploadId when event changes or dialog opens
  // themeImageUploadId is now included in Event response (Story 2.5.3a)
  useEffect(() => {
    if (open && mode === 'create') {
      // Clear upload ID when creating new event
      setThemeImageUploadId(undefined);
    } else if (Eopen && mode === 'edit' && event) {
      // Initialize from event's upload ID when editing
      setThemeImageUploadId(event.themeImageUploadId ?? undefined);
    }
  }, [event, open, mode]);
 
  // Fetch existing event tasks when opening in edit mode (Story 5.5 AC21)
  // Pre-select all default templates if no tasks exist yet
  useEffect(() => {
    if (open && mode === 'edit' && event) {
      const loadExistingTasksAndTemplates = async () => {
        try {
          // Fetch existing tasks
          const existingTasks = await taskService.listEventTasks(event.eventCode);
 
          // Find which templates already have task instances
          const templatesWithInstances = existingTasks
            .filter((task) => task.templateId !== null)
            .map((task) => task.templateId as string);
 
          if (templatesWithInstances.length > 0) {
            // Tasks exist - mark these templates as selected AND disabled
            setSelectedTemplates(templatesWithInstances);
            setDisabledTemplates(templatesWithInstances); // Disable templates with task instances
 
            // Map assignees from existing tasks
            const assigneesMap: Record<string, string> = {};
            existingTasks.forEach((task) => {
              if (task.templateId && task.assignedOrganizerUsername) {
                assigneesMap[task.templateId] = task.assignedOrganizerUsername;
              }
            });
            setTemplateAssignees(assigneesMap);
          } else {
            // No tasks exist yet - pre-select all default templates (but don't disable them)
            // Fetch all templates to get default ones
            const allTemplates = await taskService.listAllTemplates();
            const defaultTemplateIds = allTemplates
              .filter((template) => template.isDefault)
              .map((template) => template.id);
 
            setSelectedTemplates(defaultTemplateIds);
            setDisabledTemplates([]); // No templates are disabled yet
            setTemplateAssignees({});
          }
        } catch (error) {
          console.error('Failed to load existing tasks:', error);
          // Don't fail the entire dialog if task loading fails
        }
      };
 
      loadExistingTasksAndTemplates();
    }
  }, [open, mode, event]);
 
  // Create validation schema with translations
  const eventSchema = createEventSchema(t);
 
  const form = useForm<EventFormData>({
    // NOTE: Type assertion required here due to Zod limitation
    // z.coerce.number() returns 'unknown' for input type, causing type mismatch with zodResolver
    // This is safe because:
    // 1. EventFormData interface explicitly defines venueCapacity: number and eventNumber: number
    // 2. Zod schema validates and coerces the values to number at runtime
    // 3. The form will only accept/return EventFormData with these fields as numbers
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    resolver: zodResolver(eventSchema) as any,
    mode: 'onBlur',
    defaultValues: event
      ? {
          eventNumber: event.eventNumber || 1,
          title: event.title,
          description: event.description || '',
          date: event.date ? event.date.split('T')[0] : '',
          registrationDeadline: event.registrationDeadline?.split('T')[0] || '',
          venueName: event.venueName || '',
          venueAddress: event.venueAddress || '',
          venueCapacity: event.venueCapacity || 200,
          workflowState: event.workflowState || 'CREATED',
          eventType: normalizeEventType((event as EventUI).eventType),
        }
      : {
          eventNumber: 1,
          title: '',
          description: '',
          date: '',
          registrationDeadline: '',
          venueName: '',
          venueAddress: '',
          venueCapacity: 200,
          workflowState: 'CREATED' as const,
          eventType: 'FULL_DAY',
        },
  });
 
  const {
    control,
    handleSubmit,
    formState: { errors, isDirty },
    watch,
    getValues,
    reset,
    setValue,
  } = form;
 
  // AI description generation (Story 10.16)
  const { aiContentEnabled } = useFeatureFlags();
  const [aiTopic, setAiTopic] = useState<Topic | null>(null);
  const descriptionMutation = useAiGenerateDescription(event?.eventCode ?? '');
 
  useEffect(() => {
    Iif (mode === 'edit' && event?.topicCode) {
      topicService
        .getTopicById(event.topicCode)
        .then(setAiTopic)
        .catch(() => setAiTopic(null));
    } else {
      setAiTopic(null);
    }
  }, [mode, event?.topicCode]);
 
  const handleAiGenerateDescription = () => {
    descriptionMutation.mutate(undefined, {
      onSuccess: (data) => setValue('description', data.description, { shouldDirty: true }),
    });
  };
 
  // Reset form when modal opens in create mode
  useEffect(() => {
    if (open && mode === 'create') {
      reset({
        eventNumber: 1,
        title: '',
        description: '',
        date: '',
        registrationDeadline: '',
        venueName: '',
        venueAddress: '',
        venueCapacity: 200,
        workflowState: 'CREATED',
        eventType: 'FULL_DAY',
      });
    }
  }, [open, mode, reset]);
 
  // Store initial form data for partial update comparison
  useEffect(() => {
    if (event) {
      setInitialFormData({
        eventNumber: event.eventNumber || 1,
        title: event.title,
        description: event.description || '',
        date: event.date ? event.date.split('T')[0] : '',
        registrationDeadline: event.registrationDeadline?.split('T')[0] || '',
        venueName: event.venueName || '',
        venueAddress: event.venueAddress || '',
        venueCapacity: event.venueCapacity || 200,
        workflowState: event.workflowState || 'CREATED',
        eventType: normalizeEventType((event as EventUI).eventType),
      });
    }
  }, [event]);
 
  // Get changed fields for partial update (PATCH) — pure diff lives in ./eventFormSchema.
  const getChangedFields = useCallback(
    (currentData: PartialEventFormData): PartialEventFormData =>
      diffEventFields(currentData, initialFormData),
    [initialFormData]
  );
 
  // Auto-save functionality (5-second debounce, always enabled)
  const formValues = watch();
  const debouncedFormValues = useDebounce(formValues, 5000);
 
  useEffect(() => {
    Iif (mode === 'edit' && isDirty && event && hasEditPermission) {
      const changedFields = getChangedFields(debouncedFormValues);
      if (Object.keys(changedFields).length > 0) {
        handleAutoSave(changedFields);
      }
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [debouncedFormValues, mode, isDirty, event, hasEditPermission]);
 
  const handleAutoSave = async (changedFields: PartialEventFormData) => {
    if (!event) return;
 
    setAutoSaveStatus('saving');
    setApiError(null);
 
    try {
      // CRITICAL: Exclude workflowState from auto-save - workflow transitions are critical operations
      // that should ONLY happen on explicit user action (Save button), not via auto-save.
      // Auto-saving workflow transitions causes:
      // 1. Race conditions with manual save → optimistic locking conflicts (500 errors)
      // 2. Unintended state transitions without user confirmation
      // 3. Loss of override checkbox state context
      const patchFields = { ...changedFields };
      delete (patchFields as Partial<Record<string, unknown>>).workflowState;
 
      // Only proceed if there are fields to update (besides workflowState)
      if (Object.keys(patchFields).length === 0) {
        // No fields to auto-save (only workflowState changed, which we exclude)
        setAutoSaveStatus('saved');
        return;
      }
 
      // Update event fields via PATCH API
      const patchData = transformDatesForApi(patchFields);
      await updateEventMutation.mutateAsync({
        eventCode: event.eventCode,
        data: patchData,
      });
 
      setAutoSaveStatus('saved');
      setLastSavedAt(new Date());
      setInitialFormData(getValues()); // Update initial data after successful save
    } catch (error: unknown) {
      setAutoSaveStatus('error');
      const err = error as { response?: { status: number } };
      if (err.response?.status === 409) {
        setApiError(t('autoSave.conflict'));
      } else {
        setApiError(t('autoSave.failed'));
      }
    }
  };
 
  const handleCreate = async (data: EventFormData, isDraft = false) => {
    setApiError(null);
 
    Iif (!user?.username) {
      setApiError('User not authenticated');
      return;
    }
 
    try {
      // IMPORTANT: Backend expects organizerUsername (String) per Story 1.16.2
      // OpenAPI spec updated to use username as public identifier
      const createData: CreateEventRequest = {
        title: data.title,
        eventNumber: data.eventNumber,
        date: new Date(data.date).toISOString(),
        registrationDeadline: data.registrationDeadline
          ? new Date(data.registrationDeadline).toISOString()
          : '',
        venueName: data.venueName,
        venueAddress: data.venueAddress,
        venueCapacity: data.venueCapacity,
        workflowState: isDraft ? 'CREATED' : data.workflowState,
        eventType: data.eventType || 'FULL_DAY', // Required field with default
        organizerUsername: user.username, // Use username (e.g., "john.doe")
        currentAttendeeCount: 0,
        description: data.description || undefined,
        themeImageUploadId: themeImageUploadId || undefined, // Story 2.5.3a
      };
 
      // Use mutation hook for proper cache management (MVC pattern)
      const createdEvent = await createEventMutation.mutateAsync(createData);
 
      // Create tasks from selected templates (Story 5.5 AC21)
      if (selectedTemplates.length > 0) {
        const templateConfigs = selectedTemplates.map((templateId) => ({
          templateId,
          assignedOrganizerUsername: templateAssignees[templateId] || undefined,
        }));
 
        try {
          await taskService.createTasksFromTemplates(createdEvent.eventCode, {
            templates: templateConfigs,
          });
        } catch (taskError) {
          console.error('Failed to create tasks from templates:', taskError);
          // Don't fail the entire operation if task creation fails
          // Event is already created, tasks can be added later
        }
      }
 
      onSuccess?.();
      onClose();
    } catch (error: unknown) {
      const err = error as { response?: { data?: { message?: string } } };
      setApiError(err.response?.data?.message || t('errors.saveFailed'));
    }
  };
 
  const handleUpdate = async (data: EventFormData) => {
    if (!event) return;
 
    setApiError(null);
 
    try {
      const changedFields = getChangedFields(data);
 
      // Add themeImageUploadId if a new image was uploaded during this edit session
      // themeImageUploadId is only set when FileUpload component successfully uploads
      if (themeImageUploadId !== undefined) {
        (changedFields as Record<string, unknown>).themeImageUploadId = themeImageUploadId;
      }
 
      // Only skip update if no event fields changed AND no templates selected
      if (Object.keys(changedFields).length === 0 && selectedTemplates.length === 0) {
        onClose();
        return;
      }
 
      // Check if workflowState changed - handle separately via workflow transition API
      const workflowStateChanged = 'workflowState' in changedFields;
      const newWorkflowState = changedFields.workflowState as
        | components['schemas']['EventWorkflowState']
        | undefined;
 
      // Remove workflowState from patch data - it goes through separate API
      const patchFields = { ...changedFields };
      delete (patchFields as Partial<Record<string, unknown>>).workflowState;
 
      // Update event fields (if any changed besides workflowState)
      let updatedEvent: Event | undefined;
      if (Object.keys(patchFields).length > 0) {
        const patchData = transformDatesForApi(patchFields);
        updatedEvent = await updateEventMutation.mutateAsync({
          eventCode: event.eventCode,
          data: patchData,
        });
      }
 
      // Handle workflow state transition separately via workflow transition API
      if (workflowStateChanged && newWorkflowState) {
        await workflowService.transitionWorkflowState(
          event.eventCode,
          newWorkflowState,
          overrideValidation,
          overrideReason || undefined
        );
 
        // Immediately update all cached event objects with the new workflowState so the
        // UI reflects the change without waiting for a background refetch.
        queryClient.setQueriesData(
          { queryKey: ['event', event.eventCode] },
          (old: Event | undefined) => (old ? { ...old, workflowState: newWorkflowState } : old)
        );
        queryClient.setQueriesData({ queryKey: ['events'] }, (old: unknown) => {
          if (!old || typeof old !== 'object') return old;
          const list = old as { data?: Event[] };
          if (!list.data) return old;
          return {
            ...list,
            data: list.data.map((e: Event) =>
              e.eventCode === event.eventCode ? { ...e, workflowState: newWorkflowState } : e
            ),
          };
        });
 
        // Invalidate to trigger background refetches for fully fresh data
        queryClient.invalidateQueries({ queryKey: ['events'] });
        queryClient.invalidateQueries({ queryKey: ['event', event.eventCode] });
        queryClient.invalidateQueries({ queryKey: ['eventWorkflow', event.eventCode] });
        queryClient.invalidateQueries({ queryKey: ['events', 'current'] });
      }
 
      // Create tasks from selected templates (Story 5.5 AC21)
      // Backend is idempotent - only creates tasks that don't already exist
      console.log('=== Task Creation Debug ===');
      console.log('selectedTemplates:', selectedTemplates);
      console.log('templateAssignees:', templateAssignees);
      console.log('selectedTemplates.length:', selectedTemplates.length);
 
      if (selectedTemplates.length > 0) {
        const templateConfigs = selectedTemplates.map((templateId) => ({
          templateId,
          assignedOrganizerUsername: templateAssignees[templateId] || undefined,
        }));
 
        console.log('Creating tasks with configs:', templateConfigs);
 
        try {
          const createdTasks = await taskService.createTasksFromTemplates(event.eventCode, {
            templates: templateConfigs,
          });
 
          console.log('✓ Successfully created tasks:', createdTasks);
 
          // Invalidate tasks cache to show newly created tasks
          queryClient.invalidateQueries({ queryKey: ['tasks'] });
        } catch (taskError) {
          console.error('❌ Failed to create tasks from templates:', taskError);
          // Don't fail the entire operation if task creation fails
          // Event is already updated, tasks can be added later
        }
      } else {
        console.log('⚠️ No templates selected, skipping task creation');
      }
 
      // Pass the updated event to onSuccess callback (used for redirect if eventCode changed)
      onSuccess?.(updatedEvent);
      onClose();
    } catch (error: unknown) {
      const err = error as { response?: { data?: { message?: string } } };
      setApiError(err.response?.data?.message || t('errors.saveFailed'));
    }
  };
 
  const handleSaveClick = handleSubmit((data: EventFormData) => {
    if (mode === 'create') {
      handleCreate(data, false);
    } else {
      handleUpdate(data);
    }
  });
 
  const handleSaveDraftClick = () => {
    const data = getValues();
    handleCreate(data, true);
  };
 
  const handleCloseClick = () => {
    Iif (isDirty && mode === 'edit') {
      setShowUnsavedWarning(true);
    } else {
      onClose();
    }
  };
 
  const handleConfirmClose = () => {
    setShowUnsavedWarning(false);
    onClose();
  };
 
  const handleCancelClose = () => {
    setShowUnsavedWarning(false);
  };
 
  // Don't show permission error while auth is still loading
  Iif (!isAuthLoading && !hasEditPermission) {
    return (
      <Dialog open={open} onClose={onClose} maxWidth="sm" fullWidth fullScreen={isMobile}>
        <DialogContent>
          <Alert severity="error">{t('errors.unauthorized')}</Alert>
        </DialogContent>
        <DialogActions>
          <Button onClick={onClose}>{t('common:actions.cancel')}</Button>
        </DialogActions>
      </Dialog>
    );
  }
 
  return (
    <>
      <Dialog
        open={open}
        onClose={handleCloseClick}
        maxWidth="md"
        fullWidth
        fullScreen={isMobile}
        data-testid={mode === 'create' ? 'create-event-modal' : 'event-edit-modal'}
      >
        <DialogTitle data-testid="event-form-dialog-title">
          {mode === 'create' ? t('form.createEvent') : t('form.editEvent')}
        </DialogTitle>
 
        {/* Tabs - Story 5.5 Phase 6 */}
        <Box sx={{ borderBottom: 1, borderColor: 'divider' }}>
          <Tabs value={currentTab} onChange={(_, newValue) => setCurrentTab(newValue)}>
            <Tab label={t('tabs.info', 'Info')} data-testid="info-tab" />
            <Tab
              label={t('tabs.tasks', 'Tasks')}
              disabled={mode === 'create'}
              data-testid="tasks-tab"
            />
          </Tabs>
        </Box>
 
        <DialogContent>
          {/* Tab Panel 0: Info (Event Form) */}
          {currentTab === 0 && (
            <Box
              sx={{ pt: 2 }}
              data-testid={mode === 'create' ? 'create-event-form' : 'event-edit-form'}
            >
              {apiError && (
                <Alert severity="error" sx={{ mb: 2 }}>
                  {apiError}
                </Alert>
              )}
 
              {mode === 'edit' && (
                <Box
                  sx={{ mb: 2, display: 'flex', alignItems: 'center', gap: 1 }}
                  data-testid="auto-save-indicator"
                >
                  <Typography variant="caption" color="text.secondary">
                    {t('autoSave.enabled')}
                  </Typography>
                  {autoSaveStatus === 'saving' && (
                    <Chip label={t('common:actions.saving')} size="small" color="info" />
                  )}
                  {autoSaveStatus === 'saved' && lastSavedAt && (
                    <Chip
                      label={t('autoSave.saved', {
                        time: lastSavedAt.toLocaleTimeString(),
                      })}
                      size="small"
                      color="success"
                    />
                  )}
                  {autoSaveStatus === 'error' && (
                    <Chip label={t('autoSave.failed')} size="small" color="error" />
                  )}
                </Box>
              )}
 
              {/* Event Number and Title side-by-side */}
              <Box sx={{ display: 'flex', gap: 2, flexDirection: { xs: 'column', sm: 'row' } }}>
                <Controller
                  name="eventNumber"
                  control={control}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label={t('form.eventNumber')}
                      type="number"
                      error={!!errors.eventNumber}
                      helperText={errors.eventNumber?.message}
                      margin="normal"
                      data-testid="event-number-field"
                      sx={{ width: { xs: '100%', sm: '150px' } }}
                    />
                  )}
                />
                <Controller
                  name="title"
                  control={control}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label={t('common:labels.title')}
                      fullWidth
                      required
                      error={!!errors.title}
                      helperText={errors.title?.message}
                      margin="normal"
                      data-testid="event-title-field"
                    />
                  )}
                />
              </Box>
 
              <Box sx={{ position: 'relative' }}>
                <Controller
                  name="description"
                  control={control}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label={t('common:labels.description')}
                      fullWidth
                      multiline
                      rows={4}
                      error={!!errors.description}
                      helperText={errors.description?.message}
                      margin="normal"
                      data-testid="event-description-field"
                    />
                  )}
                />
                {aiContentEnabled && mode === 'edit' && event?.topicCode && (
                  <Tooltip title={tOrg('aiAssist.generateDescription', '✨ Generate with AI')}>
                    <span style={{ position: 'absolute', top: 20, right: 4 }}>
                      <IconButton
                        size="small"
                        onClick={handleAiGenerateDescription}
                        disabled={descriptionMutation.isPending || !aiTopic}
                        color="primary"
                        data-testid="ai-generate-description-btn"
                      >
                        {descriptionMutation.isPending ? (
                          <CircularProgress size={14} color="inherit" />
                        ) : (
                          <AutoAwesome fontSize="small" />
                        )}
                      </IconButton>
                    </span>
                  </Tooltip>
                )}
              </Box>
 
              {/* Event Date and Registration Deadline side-by-side */}
              <Box sx={{ display: 'flex', gap: 2, flexDirection: { xs: 'column', sm: 'row' } }}>
                <Controller
                  name="date"
                  control={control}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label={t('form.eventDate')}
                      type="date"
                      fullWidth
                      error={!!errors.date}
                      helperText={errors.date?.message}
                      margin="normal"
                      data-testid="event-date-field"
                      slotProps={{ inputLabel: { shrink: true } }}
                    />
                  )}
                />
                <Controller
                  name="registrationDeadline"
                  control={control}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label={t('form.registrationDeadline')}
                      type="date"
                      fullWidth
                      error={!!errors.registrationDeadline}
                      helperText={errors.registrationDeadline?.message}
                      margin="normal"
                      data-testid="registration-deadline-field"
                      slotProps={{ inputLabel: { shrink: true } }}
                    />
                  )}
                />
              </Box>
 
              {/* Event Type and Venue Capacity side-by-side */}
              <Box sx={{ display: 'flex', gap: 2, flexDirection: { xs: 'column', sm: 'row' } }}>
                <Controller
                  name="eventType"
                  control={control}
                  render={({ field }) => (
                    <Box sx={{ flex: 1, mt: 2 }}>
                      <EventTypeSelector
                        value={field.value || 'FULL_DAY'}
                        onChange={field.onChange}
                        disabled={!hasEditPermission}
                        error={!!errors.eventType}
                        helperText={errors.eventType?.message}
                      />
                    </Box>
                  )}
                />
                <Controller
                  name="venueCapacity"
                  control={control}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label={t('form.capacity')}
                      type="number"
                      fullWidth
                      required
                      error={!!errors.venueCapacity}
                      helperText={errors.venueCapacity?.message}
                      margin="normal"
                      data-testid="venue-capacity-field"
                    />
                  )}
                />
              </Box>
 
              <Controller
                name="workflowState"
                control={control}
                render={({ field }) => (
                  <FormControl fullWidth margin="normal" error={!!errors.workflowState}>
                    <InputLabel>{t('common:labels.status')}</InputLabel>
                    <Select
                      {...field}
                      label={t('common:labels.status')}
                      data-testid="event-status-select"
                    >
                      <MenuItem value="CREATED" data-testid="status-option-CREATED">
                        {t('workflow.states.created')}
                      </MenuItem>
                      <MenuItem value="TOPIC_SELECTION" data-testid="status-option-TOPIC_SELECTION">
                        {t('workflow.states.topic_selection')}
                      </MenuItem>
                      <MenuItem
                        value="SPEAKER_IDENTIFICATION"
                        data-testid="status-option-SPEAKER_IDENTIFICATION"
                      >
                        {t('workflow.states.speaker_identification')}
                      </MenuItem>
                      <MenuItem value="SLOT_ASSIGNMENT" data-testid="status-option-SLOT_ASSIGNMENT">
                        {t('workflow.states.slot_assignment')}
                      </MenuItem>
                      <MenuItem
                        value="AGENDA_PUBLISHED"
                        data-testid="status-option-AGENDA_PUBLISHED"
                      >
                        {t('workflow.states.agenda_published')}
                      </MenuItem>
                      <MenuItem value="EVENT_LIVE" data-testid="status-option-EVENT_LIVE">
                        {t('workflow.states.event_live')}
                      </MenuItem>
                      <MenuItem value="EVENT_COMPLETED" data-testid="status-option-EVENT_COMPLETED">
                        {t('workflow.states.event_completed')}
                      </MenuItem>
                      <MenuItem value="ARCHIVED" data-testid="status-option-ARCHIVED">
                        {t('workflow.states.archived')}
                      </MenuItem>
                    </Select>
                    {errors.workflowState && (
                      <FormHelperText>{errors.workflowState.message}</FormHelperText>
                    )}
                  </FormControl>
                )}
              />
 
              {/* Override Workflow Validation Checkbox */}
              <Box
                sx={{
                  mt: 2,
                  p: 2,
                  bgcolor: 'warning.light',
                  borderRadius: 1,
                  border: '1px solid',
                  borderColor: 'warning.main',
                }}
              >
                <FormControlLabel
                  control={
                    <Checkbox
                      checked={overrideValidation}
                      onChange={(e) => setOverrideValidation(e.target.checked)}
                      data-testid="override-workflow-validation-checkbox"
                    />
                  }
                  label={t('form.overrideValidation')}
                />
 
                {overrideValidation && (
                  <TextField
                    fullWidth
                    multiline
                    rows={2}
                    label={t('form.overrideReason')}
                    value={overrideReason}
                    onChange={(e) => setOverrideReason(e.target.value)}
                    placeholder={t('form.overrideReasonPlaceholder')}
                    sx={{ mt: 1 }}
                    helperText={t('form.overrideReasonHelp')}
                  />
                )}
              </Box>
 
              <Controller
                name="venueName"
                control={control}
                render={({ field }) => (
                  <TextField
                    {...field}
                    label={t('form.venue')}
                    fullWidth
                    margin="normal"
                    placeholder={t('eventForm.venue.namePlaceholder')}
                    data-testid="venue-name-field"
                  />
                )}
              />
 
              <Controller
                name="venueAddress"
                control={control}
                render={({ field }) => (
                  <TextField
                    {...field}
                    label={t('form.venueAddress')}
                    fullWidth
                    margin="normal"
                    placeholder={t('eventForm.venue.addressPlaceholder')}
                    data-testid="venue-address-field"
                  />
                )}
              />
 
              {/* Theme Image Upload - Story 2.5.3a */}
              <Box sx={{ mt: 3, pt: 3, borderTop: 1, borderColor: 'divider' }}>
                <Typography variant="subtitle2" gutterBottom>
                  {t('form.themeImage')}
                </Typography>
                <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
                  {t('form.themeImageHelp')}
                </Typography>
                <FileUpload
                  currentFileUrl={event?.themeImageUrl ?? undefined}
                  onUploadSuccess={(data) => setThemeImageUploadId(data.uploadId)}
                  onUploadError={(error) => {
                    setApiError(t(`errors.${error.type}`, { defaultValue: error.message }));
                  }}
                  onFileRemove={() => setThemeImageUploadId('')}
                  maxFileSize={5 * 1024 * 1024}
                  allowedTypes={['image/png', 'image/jpeg', 'image/svg+xml']}
                  altText={t('form.themeImageAlt')}
                  removeButtonLabel={t('form.removeThemeImage')}
                />
              </Box>
            </Box>
          )}
 
          {/* Tab Panel 1: Tasks (EventTasksTab) - Story 5.5 Phase 6 */}
          {currentTab === 1 && mode === 'edit' && (
            <Box sx={{ pt: 2 }}>
              <EventTasksTab
                eventId={event?.eventCode || null}
                organizerUsername={user?.username || ''}
                selectedTemplates={selectedTemplates}
                templateAssignees={templateAssignees}
                customTasks={customTasks}
                disabledTemplates={disabledTemplates} // Templates with task instances are disabled
                onTemplateToggle={(templateId, checked) => {
                  if (checked) {
                    setSelectedTemplates([...selectedTemplates, templateId]);
                  } else {
                    setSelectedTemplates(selectedTemplates.filter((id) => id !== templateId));
                  }
                }}
                onAssigneeChange={(templateId, assignee) => {
                  setTemplateAssignees({ ...templateAssignees, [templateId]: assignee });
                }}
                onAddCustomTask={() => {
                  // Custom task modal handled internally by EventTasksTab
                }}
                onEditCustomTask={(task) => {
                  // Edit modal handled internally by EventTasksTab
                  console.log('Edit task:', task);
                }}
                onDeleteCustomTask={(taskId) => {
                  setCustomTasks(customTasks.filter((t) => t.id !== taskId));
                }}
              />
            </Box>
          )}
        </DialogContent>
        <DialogActions sx={{ flexWrap: 'wrap', gap: 1, px: 2, pb: 2 }}>
          <Button onClick={handleCloseClick} data-testid="close-edit-modal-button">
            {t('common:actions.cancel')}
          </Button>
          {mode === 'create' && (
            <Button
              onClick={handleSaveDraftClick}
              color="secondary"
              data-testid="save-draft-event-button"
            >
              {t('form.saveDraft')}
            </Button>
          )}
          <Button
            onClick={handleSaveClick}
            variant="contained"
            color="primary"
            data-testid={mode === 'create' ? 'save-create-event-button' : 'save-event-button'}
          >
            {mode === 'create' ? t('form.saveCreate') : t('common:actions.save')}
          </Button>
        </DialogActions>
      </Dialog>
 
      {/* Unsaved Changes Warning Dialog */}
      <Dialog
        open={showUnsavedWarning}
        onClose={handleCancelClose}
        fullScreen={isMobile}
        data-testid="unsaved-changes-dialog"
      >
        <DialogTitle>{t('confirmations.unsavedChanges')}</DialogTitle>
        <DialogContent>
          <Typography>{t('confirmations.unsavedChangesMessage')}</Typography>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCancelClose} data-testid="keep-editing-button">
            {t('common:actions.cancel')}
          </Button>
          <Button
            onClick={handleConfirmClose}
            color="error"
            variant="contained"
            data-testid="discard-changes-button"
          >
            {t('confirmations.confirm')}
          </Button>
        </DialogActions>
      </Dialog>
    </>
  );
};