<template>
  <div class="task-view">
    <div v-if="taskCountRef === 0" class="no-message">
      <div>No Tasks</div>
      <div class="sub-message">
        <button class="create-btn" @click="createTask">Create</button> a task
      </div>
    </div>

    <TaskList
      v-else
      ref="taskListRef"
      :deletable="true"
      @edit-task="(taskId) => $router.push({ name: 'EditTask', params: { id: taskId } })"
      @delete-task="confirmDeleteTask"
      @loading-complete="(count) => (taskCountRef = count)"
    />

    <!-- Floating Action Button -->
    <button class="fab" @click="createTask" aria-label="Create Task">
      <svg width="28" height="28" viewBox="0 0 28 28" fill="none">
        <circle cx="14" cy="14" r="14" fill="#667eea" />
        <path d="M14 8v12M8 14h12" stroke="#fff" stroke-width="2" stroke-linecap="round" />
      </svg>
    </button>

    <div v-if="showConfirm" class="modal-backdrop">
      <div class="modal">
        <p>Are you sure you want to delete this task?</p>
        <div class="actions">
          <button @click="deleteTask" class="btn btn-danger">Delete</button>
          <button @click="showConfirm = false" class="btn btn-secondary">Cancel</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import TaskList from './TaskList.vue'

const $router = useRouter()

const showConfirm = ref(false)
const taskToDelete = ref<string | null>(null)
const taskListRef = ref()
const taskCountRef = ref<number>(-1)

function confirmDeleteTask(taskId: string) {
  taskToDelete.value = taskId
  showConfirm.value = true
}

const deleteTask = async () => {
  if (!taskToDelete.value) return
  try {
    const resp = await fetch(`/api/task/${taskToDelete.value}`, {
      method: 'DELETE',
    })
    if (!resp.ok) throw new Error(`HTTP ${resp.status}`)
    // Refresh the task list after successful delete
    taskListRef.value?.refresh()
  } catch (err) {
    console.error('Failed to delete task:', err)
  } finally {
    showConfirm.value = false
    taskToDelete.value = null
  }
}

// New function to handle task creation
const createTask = () => {
  // Route to your create task page or open a create dialog
  // Example:
  $router.push({ name: 'CreateTask' })
}
</script>

<style scoped>
.task-view {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1 1 auto;
  width: 100%;
  height: 100%;
  padding: 0;
  min-height: 0;
}

.create-btn {
  background: var(--task-create-btn-bg);
  color: var(--task-create-btn-color);
  border: 2px solid var(--task-create-btn-border);
  border-radius: 6px;
  font-size: 0.85rem;
  font-weight: 600;
  padding: 0.2rem 0.5rem;
  margin-right: 0.1rem;
  cursor: pointer;
  transition:
    background 0.18s,
    color 0.18s;
}
.create-btn:hover {
  background: var(--task-create-btn-hover-bg);
  color: var(--task-create-btn-hover-color);
}
</style>
