// src/client/features/tasks/model/useTaskOperations.ts
// Composable for CRUD operations in TaskCard component
//
// FIX: Added committedTitle for optimistic title display (same pattern as useTaskItemEdit)

import { ref, computed, watch, nextTick, type Ref } from 'vue';
import { useTaskStore } from '../../../entities/task';
import type { Task } from '@shared/contracts/tasks';

export function useTaskOperations(
  rootTask: Ref<Task>,
  emit: any
) {
  const taskStore = useTaskStore();

  // Title editing state
  const isEditingTitle = ref(false);
  const editTitle = ref(rootTask.value.text);

  // Optimistic title — shows immediately after edit, syncs when store updates
  const committedTitle = ref(rootTask.value.text);

  // Sync when the store/prop updates (server response, external change)
  watch(() => rootTask.value.text, (newText) => {
    committedTitle.value = newText;
  });

  // Ref for the last TaskItem component to enable auto-focus
  const lastTaskItemRef = ref<any>(null);

  // Computed for title display — uses committedTitle for instant feedback
  const displayTitle = computed(() => {
    return isEditingTitle.value ? editTitle.value : committedTitle.value;
  });

  // Start editing title
  const startEditTitle = () => {
    isEditingTitle.value = true;
    editTitle.value = committedTitle.value;
  };

  // Finish editing title
  const finishEditTitle = async () => {
    const trimmed = editTitle.value.trim();
    if (trimmed && trimmed !== committedTitle.value) {
      committedTitle.value = trimmed; // ← optimistic update
      try {
        await taskStore.updateTask(rootTask.value.id, {
          text: trimmed,
        });
      } catch (error) {
        // Revert on failure
        committedTitle.value = rootTask.value.text;
        console.error('Failed to update task:', error);
      }
    }
    isEditingTitle.value = false;
  };

  // Cancel editing title
  const cancelEditTitle = () => {
    editTitle.value = committedTitle.value;
    isEditingTitle.value = false;
  };

  // Handle Enter key for title
  const handleTitleKeydown = (e: KeyboardEvent) => {
    if (e.key === 'Enter') {
      e.preventDefault();
      finishEditTitle();
    } else if (e.key === 'Escape') {
      cancelEditTitle();
    }
  };

  // Handle blur for title
  const handleTitleBlur = () => {
    if (editTitle.value.trim() !== committedTitle.value) {
      finishEditTitle();
    } else {
      cancelEditTitle();
    }
  };

  // Focus title input when editing starts
  const titleInputRef = ref<HTMLInputElement>();
  const focusTitleInput = () => {
    titleInputRef.value?.focus();
  };

  // Watch for editing changes to focus input
  watch(isEditingTitle, (newVal) => {
    if (newVal) {
      setTimeout(focusTitleInput, 0);
    }
  });

  // Update subtask text
  const updateSubtaskText = async (subtaskId: string, text: string) => {
    try {
      await taskStore.updateTask(subtaskId, { text });
    } catch (error) {
      console.error('Failed to update subtask:', error);
    }
  };

  // Toggle subtask completion
  const toggleSubtask = async (subtaskId: string, completed: boolean) => {
    try {
      await taskStore.updateTask(subtaskId, { isCompleted: completed });
    } catch (error) {
      console.error('Failed to toggle subtask:', error);
    }
  };

  // Add new subtask
  const addSubtask = async (allTasksFlat: Task[]) => {
    try {
      const level1Tasks = taskStore.getChildTasks(rootTask.value.id).filter(t => t.parentId === rootTask.value.id);
      const newTask = await taskStore.createTask({
        text: '',
        isCompleted: false,
        parentId: rootTask.value.id,
        order: level1Tasks.length,
      });

      // Auto-focus on new subtask (last item in the list)
      await nextTick();
      if (lastTaskItemRef.value) {
        lastTaskItemRef.value.focusInput();
      }
    } catch (error) {
      console.error('Failed to add subtask:', error);
    }
  };

  // Delete subtask
  const deleteSubtask = async (subtaskId: string) => {
    try {
      await taskStore.deleteTask(subtaskId);
    } catch (error) {
      console.error('Failed to delete subtask:', error);
    }
  };

  // Delete entire card
  const deleteCard = async () => {
    emit('delete');
  };

  // Add subtask on button click
  const handleAddSubtaskClick = (allTasksFlat: Task[]) => {
    addSubtask(allTasksFlat);
  };

  // Function to set ref for the last task item
  const setLastTaskItemRef = (el: any) => {
    if (el) {
      lastTaskItemRef.value = el;
    }
  };

  return {
    isEditingTitle,
    editTitle,
    titleInputRef,
    displayTitle,
    startEditTitle,
    finishEditTitle,
    cancelEditTitle,
    handleTitleKeydown,
    handleTitleBlur,
    updateSubtaskText,
    toggleSubtask,
    addSubtask,
    deleteSubtask,
    deleteCard,
    handleAddSubtaskClick,
    setLastTaskItemRef,
    lastTaskItemRef,
  };
}