<template>
  <div class="flex flex-col h-full">
    <!-- Notes History (Top) -->
    <div class="flex-1 overflow-y-auto p-2 space-y-2">
      <div v-if="notes.length === 0" class="flex flex-col items-center justify-center h-full text-muted-foreground">
        <MessageSquarePlus class="h-10 w-10 mb-2 opacity-50" />
        <p class="text-sm">No notes yet. Start the conversation below.</p>
      </div>

      <NoteItem
        v-for="note in notes"
        :key="note.id"
        :note="note"
        :task-id="taskId"
        @note-updated="emit('notesUpdated')"
        @reply="handleReply"
      />
    </div>

    <!-- Note Input (Bottom) -->
    <div class="flex-shrink-0 border-t bg-background p-2">
      <div class="space-y-2">
        <Textarea
          v-model="newNoteContent"
          placeholder="Add a note..."
          rows="2"
          class="resize-none text-sm"
        />
        <div class="flex justify-end">
          <Button
            @click="handleAddNote"
            :disabled="!newNoteContent.trim() || submitting"
            size="sm"
          >
            <MessageSquarePlus class="h-4 w-4 mr-2" />
            Add Note
          </Button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { MessageSquarePlus } from 'lucide-vue-next'
import { Button } from '@/components/ui/button'
import { Textarea } from '@/components/ui/textarea'
import NoteItem from './NoteItem.vue'
import { taskService, type ProductionNote } from '@/services/task'
import { useToast } from '@/components/ui/toast/use-toast'

const props = defineProps<{
  taskId: number
  notes: ProductionNote[]
}>()

const emit = defineEmits<{
  notesUpdated: []
}>()

const { toast } = useToast()

const newNoteContent = ref('')
const submitting = ref(false)
const replyToNoteId = ref<number | null>(null)

async function handleAddNote() {
  if (!newNoteContent.value.trim()) return

  submitting.value = true
  try {
    await taskService.createTaskNote(
      props.taskId,
      newNoteContent.value,
      replyToNoteId.value || undefined
    )
    newNoteContent.value = ''
    replyToNoteId.value = null
    emit('notesUpdated')
    toast({
      title: 'Success',
      description: 'Note added successfully'
    })
  } catch (error: any) {
    console.error('Error adding note:', error)
    toast({
      title: 'Error',
      description: error.response?.data?.detail || 'Failed to add note',
      variant: 'destructive'
    })
  } finally {
    submitting.value = false
  }
}

function handleReply(noteId: number) {
  replyToNoteId.value = noteId
  // Focus on textarea (you could add a ref for this)
}
</script>
