<template>
  <div class="space-y-2">
    <div class="flex gap-3">
      <!-- Avatar -->
      <div class="flex-shrink-0">
        <Avatar class="h-8 w-8">
          <AvatarImage
            v-if="note.user_id"
            :src="getAvatarUrl(note.user_avatar_url, note.user_first_name, note.user_last_name)"
          />
          <AvatarImage
            v-else
            :src="`https://ui-avatars.com/api/?name=${note.user_first_name} ${note.user_last_name}`"
          />
          <AvatarFallback>
            {{ getInitials(note.user_first_name, note.user_last_name) }}
          </AvatarFallback>
        </Avatar>
      </div>

      <!-- Content -->
      <div class="flex-1 space-y-1">
        <div class="flex items-center gap-2">
          <span class="font-semibold text-sm">
            {{ note.user_first_name }} {{ note.user_last_name }}
          </span>
          <span class="text-xs text-muted-foreground">
            {{ formatDateTime(note.created_at) }}
          </span>
          <span v-if="note.updated_at !== note.created_at" class="text-xs text-muted-foreground">
            (edited)
          </span>
        </div>

        <!-- Note Content -->
        <div v-if="!editing" class="text-sm whitespace-pre-wrap">
          {{ note.content }}
        </div>

        <!-- Edit Form -->
        <div v-else class="space-y-2">
          <Textarea
            v-model="editContent"
            rows="3"
            class="resize-none"
          />
          <div class="flex gap-2">
            <Button size="sm" @click="handleSave">Save</Button>
            <Button size="sm" variant="outline" @click="editing = false">Cancel</Button>
          </div>
        </div>

        <!-- Actions -->
        <div v-if="!editing" class="flex gap-2">
          <Button
            variant="ghost"
            size="sm"
            @click="emit('reply', note.id)"
          >
            <Reply class="h-3 w-3 mr-1" />
            Reply
          </Button>
          <Button
            v-if="canEdit"
            variant="ghost"
            size="sm"
            @click="startEdit"
          >
            <Pencil class="h-3 w-3 mr-1" />
            Edit
          </Button>
          <Button
            v-if="canDelete"
            variant="ghost"
            size="sm"
            @click="handleDelete"
          >
            <Trash2 class="h-3 w-3 mr-1" />
            Delete
          </Button>
        </div>

        <!-- Child Notes (Threaded) -->
        <div v-if="note.child_notes && note.child_notes.length > 0" class="mt-4 space-y-4 pl-4 border-l-2">
          <NoteItem
            v-for="childNote in note.child_notes"
            :key="childNote.id"
            :note="childNote"
            :task-id="taskId"
            @note-updated="emit('noteUpdated')"
            @reply="emit('reply', $event)"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { Reply, Pencil, Trash2 } from 'lucide-vue-next'
import { Button } from '@/components/ui/button'
import { Textarea } from '@/components/ui/textarea'
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'
import { taskService, type ProductionNote } from '@/services/task'
import { useAuthStore } from '@/stores/auth'
import { useToast } from '@/components/ui/toast/use-toast'

const props = defineProps<{
  note: ProductionNote
  taskId: number
}>()

const emit = defineEmits<{
  noteUpdated: []
  reply: [noteId: number]
}>()

const { toast } = useToast()
const authStore = useAuthStore()

const editing = ref(false)
const editContent = ref('')

const canEdit = computed(() => {
  return authStore.user?.id === props.note.user_id || authStore.user?.is_admin
})

const canDelete = computed(() => {
  return authStore.user?.id === props.note.user_id || authStore.user?.is_admin
})

function getInitials(firstName: string, lastName: string): string {
  return `${firstName.charAt(0)}${lastName.charAt(0)}`.toUpperCase()
}

function formatDateTime(dateString: string): string {
  const date = new Date(dateString)
  const now = new Date()
  const diffMs = now.getTime() - date.getTime()
  const diffMins = Math.floor(diffMs / 60000)
  const diffHours = Math.floor(diffMs / 3600000)
  const diffDays = Math.floor(diffMs / 86400000)

  if (diffMins < 1) return 'just now'
  if (diffMins < 60) return `${diffMins}m ago`
  if (diffHours < 24) return `${diffHours}h ago`
  if (diffDays < 7) return `${diffDays}d ago`

  return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })
}

function startEdit() {
  editing.value = true
  editContent.value = props.note.content
}

async function handleSave() {
  try {
    await taskService.updateTaskNote(props.taskId, props.note.id, editContent.value)
    editing.value = false
    emit('noteUpdated')
    toast({
      title: 'Success',
      description: 'Note updated successfully'
    })
  } catch (error: any) {
    console.error('Error updating note:', error)
    toast({
      title: 'Error',
      description: error.response?.data?.detail || 'Failed to update note',
      variant: 'destructive'
    })
  }
}

async function handleDelete() {
  if (!confirm('Are you sure you want to delete this note?')) return

  try {
    await taskService.deleteTaskNote(props.taskId, props.note.id)
    emit('noteUpdated')
    toast({
      title: 'Success',
      description: 'Note deleted successfully'
    })
  } catch (error: any) {
    console.error('Error deleting note:', error)
    toast({
      title: 'Error',
      description: error.response?.data?.detail || 'Failed to delete note',
      variant: 'destructive'
    })
  }
}

import { useAvatarUrl } from '@/composables/useAvatarUrl'

const { getAvatarUrl, getInitialsAvatarUrl } = useAvatarUrl()
</script>
