// 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 { usePermissionsStore } from '@client/entities/permissions';
import { AppPermission } from '@shared/contracts/permissions';

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);
    title.value = options.note?.title || '';
    content.value = options.note?.content || '';
    priority.value = options.note?.priority || 'normal';
    status.value = options.note?.status || 'active';
    reminderAt.value = options.note?.layout?.reminderAt || null;

    if (options.mode === 'create') {
      const permissionsStore = usePermissionsStore();
      const canCreatePrivate = permissionsStore.hasPermission(AppPermission.NOTES_CREATE_PRIVATE);
      const canCreatePublic = permissionsStore.hasPermission(AppPermission.NOTES_CREATE_PUBLIC);

      // Если нет прав на личные, но есть на публичные — ставим публичную по умолчанию
      if (!canCreatePrivate && canCreatePublic) {
        isPublic.value = true;
      } else {
        isPublic.value = false;
      }
    } else {
      isPublic.value = options.note?.isPublic || false;

      if (options.note) {
        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,
        });
      }
    }

    console.log('useNoteForm: Initialized form', { mode: options.mode, isPublic: isPublic.value });
    errors.value = { title: '', content: '' };
  }

  // 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,
  };
}
