<template>
  <Popover v-model:open="isOpen">
    <PopoverAnchor
      :style="{
        position: 'fixed',
        left: `${props.position.x}px`,
        top: `${props.position.y}px`,
        width: '1px',
        height: '1px',
      }"
    />
    <PopoverContent
      class="w-56 p-1"
      :side="'bottom'"
      :align="'start'"
      @interact-outside="handleInteractOutside"
    >
      <!-- Header showing selection count -->
      <div class="px-2 py-1.5 text-sm font-semibold text-muted-foreground border-b mb-1">
        {{ selectedCount }} {{ selectedCount === 1 ? 'task' : 'tasks' }} selected
      </div>

      <!-- Validation warning if tasks from multiple projects -->
      <div v-if="hasMultipleProjects" class="px-2 py-1.5 text-xs text-destructive bg-destructive/10 rounded-sm mb-1">
        Selected tasks are from different projects
      </div>

      <!-- Set Status submenu -->
      <DropdownMenu>
        <DropdownMenuTrigger as-child>
          <button
            :disabled="isProcessing || hasMultipleProjects || isLoadingStatuses"
            class="w-full text-left px-2 py-1.5 text-sm hover:bg-accent hover:text-accent-foreground rounded-sm cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-between"
          >
            <span>Set Status</span>
            <ChevronRight class="h-4 w-4" />
          </button>
        </DropdownMenuTrigger>
        <DropdownMenuContent class="w-48" side="right" align="start">
          <!-- Loading state -->
          <div v-if="isLoadingStatuses" class="px-2 py-1.5 text-sm text-muted-foreground">
            Loading statuses...
          </div>
          
          <!-- System statuses -->
          <template v-else>
            <div v-if="systemStatuses.length > 0" class="px-2 py-1 text-xs font-semibold text-muted-foreground">
              System Statuses
            </div>
            <DropdownMenuItem
              v-for="status in systemStatuses"
              :key="status.id"
              :disabled="isProcessing"
              @click="handleStatusSelected(status.id)"
              class="flex items-center gap-2"
            >
              <div
                class="w-2 h-2 rounded-full flex-shrink-0"
                :style="{ backgroundColor: status.color }"
              />
              <span>{{ status.name }}</span>
            </DropdownMenuItem>

            <!-- Divider if both system and custom statuses exist -->
            <div v-if="systemStatuses.length > 0 && customStatuses.length > 0" class="h-px bg-border my-1" />

            <!-- Custom statuses -->
            <div v-if="customStatuses.length > 0" class="px-2 py-1 text-xs font-semibold text-muted-foreground">
              Custom Statuses
            </div>
            <DropdownMenuItem
              v-for="status in customStatuses"
              :key="status.id"
              :disabled="isProcessing"
              @click="handleStatusSelected(status.id)"
              class="flex items-center gap-2"
            >
              <div
                class="w-2 h-2 rounded-full flex-shrink-0"
                :style="{ backgroundColor: status.color }"
              />
              <span>{{ status.name }}</span>
            </DropdownMenuItem>
          </template>
        </DropdownMenuContent>
      </DropdownMenu>

      <!-- Divider -->
      <div class="h-px bg-border my-1" />

      <!-- Assign To section -->
      <div class="py-1">
        <div class="px-2 py-1.5 text-xs font-semibold text-muted-foreground">
          Assign To
        </div>
        <div v-if="projectMembers.length === 0" class="px-2 py-1.5 text-sm text-muted-foreground">
          No members available
        </div>
        <div v-else class="max-h-48 overflow-y-auto">
          <button
            v-for="member in projectMembers"
            :key="member.user_id"
            :disabled="isProcessing || hasMultipleProjects"
            class="w-full text-left px-2 py-1.5 text-sm hover:bg-accent hover:text-accent-foreground rounded-sm cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"
            @click="handleAssigneeSelected(member.user_id)"
          >
            {{ member.user_first_name }} {{ member.user_last_name }}
          </button>
        </div>
      </div>
    </PopoverContent>
  </Popover>
</template>

<script setup lang="ts">
import { ref, watch, computed, onMounted } from 'vue'
import {
  Popover,
  PopoverAnchor,
  PopoverContent,
} from '@/components/ui/popover'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import { ChevronRight } from 'lucide-vue-next'
import type { ProjectMember } from '@/services/project'
import type { Task } from '@/services/task'
import { customTaskStatusService, type CustomTaskStatus, type SystemTaskStatus } from '@/services/customTaskStatus'
import { useTaskStatusesStore } from '@/stores/taskStatuses'

interface Props {
  open: boolean
  position: { x: number; y: number }
  selectedCount: number
  selectedTasks: Task[]
  projectMembers: ProjectMember[]
  isProcessing?: boolean
}

interface Emits {
  (e: 'update:open', value: boolean): void
  (e: 'status-selected', status: string): void
  (e: 'assignee-selected', userId: number): void
}

const props = withDefaults(defineProps<Props>(), {
  isProcessing: false,
})

const emit = defineEmits<Emits>()

// Use the shared task statuses store
const taskStatusesStore = useTaskStatusesStore()

// Local state for menu open/close
const isOpen = ref(props.open)

// Computed properties
const hasMultipleProjects = computed(() => {
  if (props.selectedTasks.length === 0) return false
  const projectIds = new Set(props.selectedTasks.map(task => task.project_id))
  return projectIds.size > 1
})

const currentProjectId = computed(() => {
  if (props.selectedTasks.length === 0) return null
  return props.selectedTasks[0].project_id
})

// Get loading state from store
const isLoadingStatuses = computed(() => {
  return currentProjectId.value ? taskStatusesStore.isLoading(currentProjectId.value) : false
})

// Get status options from store
const systemStatuses = computed(() => {
  if (!currentProjectId.value) return []
  const statuses = taskStatusesStore.getProjectStatuses(currentProjectId.value)
  return statuses?.system_statuses || []
})

const customStatuses = computed(() => {
  if (!currentProjectId.value) return []
  const statuses = taskStatusesStore.getProjectStatuses(currentProjectId.value)
  return statuses?.statuses || []
})

// Methods
const fetchStatuses = async () => {
  if (!currentProjectId.value || hasMultipleProjects.value) {
    return
  }

  try {
    await taskStatusesStore.fetchProjectStatuses(currentProjectId.value)
  } catch (error) {
    console.error('Failed to fetch task statuses:', error)
  }
}

const handleStatusSelected = (status: string) => {
  emit('status-selected', status)
  isOpen.value = false
}

const handleAssigneeSelected = (userId: number) => {
  emit('assignee-selected', userId)
  isOpen.value = false
}

const handleInteractOutside = () => {
  isOpen.value = false
}

// Watch for prop changes
watch(
  () => props.open,
  (newValue) => {
    isOpen.value = newValue
    // Fetch statuses when menu opens
    if (newValue && currentProjectId.value && !hasMultipleProjects.value) {
      fetchStatuses()
    }
  }
)

// Emit changes to parent
watch(isOpen, (newValue) => {
  emit('update:open', newValue)
})

// Watch for selected tasks changes to refetch statuses if project changes
watch(
  () => currentProjectId.value,
  (newProjectId, oldProjectId) => {
    if (newProjectId && newProjectId !== oldProjectId && isOpen.value) {
      fetchStatuses()
    }
  }
)

// Fetch statuses on mount if menu is already open
onMounted(() => {
  if (isOpen.value && currentProjectId.value && !hasMultipleProjects.value) {
    fetchStatuses()
  }
})
</script>
