// src/client/entities/note/model/useNoteForm.ts
// Hook for managing note form state and validation

import { ref, watch, type Ref } from 'vue';
import type { Note, NotePriority, NoteStatus, CreateNoteInput, UpdateNoteInput } from '@client/entities/note';
import { useUserStore } from '@client/entities/user';
import { USER_ROLES } from '@shared/constants/roles';

export interface NoteFormErrors {
  title: string;
  content: string;
}

export interface UseNoteFormOptions {
  mode: 'create' | 'edit';
  note?: Note;
}

export interface UseNoteFormReturn {
  // Form state
  title: Ref<string>;
  content: Ref<string>;
  priority: Ref<NotePriority>;
  status: Ref<NoteStatus>;
  isPublic: Ref<boolean>;
  reminderAt: Ref<string | null>;
  
  // Validation errors
  errors: Ref<NoteFormErrors>;
  
  // Methods
  initForm: () => void;
  validate: () => boolean;
  getCreateData: () => CreateNoteInput;
  getUpdateData: (note: Note) => UpdateNoteInput;
}

export function useNoteForm(options: UseNoteFormOptions): UseNoteFormReturn {
  // Form state
  const title = ref('');
  const content = ref('');
  const priority = ref<NotePriority>('normal');
  const status = ref<NoteStatus>('active');
  const isPublic = ref(false);
  const reminderAt = ref<string | null>(null);
  
  // Validation errors
  const errors = ref<NoteFormErrors>({ title: '', content: '' });

  // Initialize form based on mode and note
  function initForm(): void {
    console.log('useNoteForm: initForm called, mode:', options.mode, 'note:', options.note);
    if (options.note && options.mode === 'edit') {
      title.value = options.note.title;
      content.value = options.note.content;
      priority.value = options.note.priority;
      status.value = options.note.status;
      isPublic.value = options.note.isPublic;
      reminderAt.value = options.note.layout?.reminderAt ?? null; // reminderAt comes from layout
      console.log('useNoteForm: Initialized edit form with note:', {
        id: options.note.id,
        title: options.note.title,
        status: options.note.status,
        reminderAt: options.note.layout?.reminderAt,
      });
    } else if (options.mode === 'create') {
      // Reset form for create mode
      title.value = '';
      content.value = '';
      priority.value = 'normal';
      status.value = 'active';
      // Admin default public check
      const userStore = useUserStore();
      isPublic.value = userStore.role === USER_ROLES.ADMIN;
      reminderAt.value = null;
      console.log('useNoteForm: Initialized create form (reset)', { isAdmin: userStore.role === USER_ROLES.ADMIN, isPublic: isPublic.value });
    }
  }

  // Watch options.note to reinitialize form when note changes
  watch(() => options.note, () => initForm(), { deep: true, immediate: true });

  // Validate form
  function validate(): boolean {
    // Clear previous errors
    errors.value = { title: '', content: '' };
    
    let hasErrors = false;
    
    if (!title.value.trim()) {
      errors.value.title = 'Заголовок обязателен';
      hasErrors = true;
    }
    
    if (!content.value.trim()) {
      errors.value.content = 'Содержание обязательно';
      hasErrors = true;
    }
    
    return !hasErrors;
  }

  // Get data for create operation
  function getCreateData(): CreateNoteInput {
    return {
      title: title.value,
      content: content.value,
      priority: priority.value,
      isPublic: isPublic.value,
      reminderAt: reminderAt.value,
    };
  }

  // Get data for update operation
  function getUpdateData(note: Note): UpdateNoteInput {
    const data = {
      title: title.value,
      content: content.value,
      priority: priority.value,
      status: status.value,
      isPublic: isPublic.value,
      reminderAt: reminderAt.value,
    };
    console.log('useNoteForm: getUpdateData returning:', {
      ...data,
      noteId: note.id,
    });
    return data;
  }


  // Watchers to clear errors when user starts typing
  watch(title, () => {
    if (errors.value.title) {
      errors.value.title = '';
    }
  });

  watch(content, () => {
    if (errors.value.content) {
      errors.value.content = '';
    }
  });

  return {
    title,
    content,
    priority,
    status,
    isPublic,
    reminderAt,
    errors,
    initForm,
    validate,
    getCreateData,
    getUpdateData,
  };
}
