<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { ListFilter } from 'lucide-vue-next'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from '@/components/ui/popover'
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandList,
  CommandSeparator,
  CheckableCommandItem,
} from '@/components/ui/command'
import TaskStatusBadge from '@/components/status/TaskStatusBadge.vue'
import { useTaskStatusesStore } from '@/stores/taskStatuses'

interface Props {
  allTaskTypes: string[]
  projectId?: number
}

const props = defineProps<Props>()

const emit = defineEmits<{
  'filter-changed': [filter: string]
}>()

const taskStatusesStore = useTaskStatusesStore()
const selectedFilters = ref<string[]>([])

// System status options (fallback if no project ID / statuses not loaded yet)
const defaultStatusOptions = [
  { id: 'not_started', name: 'Not Started', color: '', is_system: true },
  { id: 'in_progress', name: 'In Progress', color: '', is_system: true },
  { id: 'submitted', name: 'Submitted', color: '', is_system: true },
  { id: 'approved', name: 'Approved', color: '', is_system: true },
  { id: 'retake', name: 'Retake', color: '', is_system: true },
]

const allStatuses = computed(() => {
  if (!props.projectId) return defaultStatusOptions

  const statusData = taskStatusesStore.getProjectStatuses(props.projectId)
  if (!statusData) return defaultStatusOptions

  const systemStatusList = statusData.system_statuses.map(s => ({
    id: s.id, name: s.name, color: s.color, is_system: s.is_system,
  }))
  const customStatusList = statusData.statuses.map(s => ({
    id: s.id, name: s.name, color: s.color, is_system: false,
  }))
  return [...systemStatusList, ...customStatusList]
})

const loadStatuses = async () => {
  if (!props.projectId) return
  try {
    await taskStatusesStore.fetchProjectStatuses(props.projectId)
  } catch (error) {
    console.error('Failed to load task statuses:', error)
  }
}

onMounted(loadStatuses)
watch(() => props.projectId, loadStatuses)

const toggleFilter = (filter: string) => {
  const index = selectedFilters.value.indexOf(filter)
  if (index > -1) {
    selectedFilters.value.splice(index, 1)
  } else {
    selectedFilters.value.push(filter)
  }
  const apiFilter = selectedFilters.value.length > 0 ? selectedFilters.value.join(',') : ''
  emit('filter-changed', apiFilter)
}

const clearAllFilters = () => {
  selectedFilters.value = []
  emit('filter-changed', '')
}

const formatTaskType = (taskType: string) =>
  taskType.charAt(0).toUpperCase() + taskType.slice(1)
</script>

<template>
  <Popover>
    <PopoverTrigger as-child>
      <Button variant="outline" size="sm" class="h-8 border-dashed">
        <ListFilter class="mr-2 h-4 w-4" />
        Task Status
        <Badge
          v-if="selectedFilters.length > 0"
          variant="secondary"
          class="ml-2 rounded-sm px-1 font-normal"
        >
          {{ selectedFilters.length }}
        </Badge>
      </Button>
    </PopoverTrigger>
    <PopoverContent class="w-[220px] p-0" align="start">
      <Command>
        <CommandInput placeholder="Search task status..." />
        <CommandList>
          <CommandEmpty>No status found.</CommandEmpty>

          <!-- All Tasks Option -->
          <CommandGroup>
            <CheckableCommandItem
              value="all"
              :model-value="selectedFilters.length === 0"
              @update:model-value="clearAllFilters"
            >
              <span>All Tasks</span>
            </CheckableCommandItem>
          </CommandGroup>

          <!-- Task Type Groups -->
          <CommandGroup v-for="taskType in allTaskTypes" :key="taskType">
            <CommandSeparator />
            <div class="px-2 py-1.5 text-xs font-medium text-muted-foreground">
              {{ formatTaskType(taskType) }}
            </div>
            <CheckableCommandItem
              v-for="status in allStatuses"
              :key="`${taskType}:${status.id}`"
              :value="`${taskType}:${status.id}`"
              :model-value="selectedFilters.includes(`${taskType}:${status.id}`)"
              @update:model-value="toggleFilter(`${taskType}:${status.id}`)"
            >
              <div class="flex items-center gap-2">
                <TaskStatusBadge :status="status as any" />
              </div>
            </CheckableCommandItem>
          </CommandGroup>
        </CommandList>
      </Command>
    </PopoverContent>
  </Popover>
</template>
