<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>
            <CommandItem value="all" @select="clearAllFilters">
              <div
                :class="[
                  'mr-2 flex h-4 w-4 items-center justify-center rounded-sm border border-primary',
                  selectedFilters.length === 0
                    ? 'bg-primary text-primary-foreground'
                    : 'opacity-50 [&_svg]:invisible'
                ]"
              >
                <Check class="h-4 w-4" />
              </div>
              <span>All Tasks</span>
            </CommandItem>
          </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>
            <CommandItem
              v-for="status in allStatuses"
              :key="`${taskType}:${status.id}`"
              :value="`${taskType}:${status.id}`"
              @select="toggleFilter(`${taskType}:${status.id}`)"
            >
              <div
                :class="[
                  'mr-2 flex h-4 w-4 items-center justify-center rounded-sm border border-primary',
                  selectedFilters.includes(`${taskType}:${status.id}`)
                    ? 'bg-primary text-primary-foreground'
                    : 'opacity-50 [&_svg]:invisible'
                ]"
              >
                <Check class="h-4 w-4" />
              </div>
              <div class="flex items-center gap-2">
                <TaskStatusBadge :status="status as any" />
              </div>
            </CommandItem>
          </CommandGroup>
        </CommandList>
      </Command>
    </PopoverContent>
  </Popover>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { ListFilter, Check } 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,
  CommandItem,
  CommandList,
  CommandSeparator,
} from '@/components/ui/command'
import TaskStatusBadge from '@/components/status/TaskStatusBadge.vue'
import { TaskStatus } from '@/services/asset'
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[]>([])

const defaultStatusOptions = [
  { id: TaskStatus.NOT_STARTED, name: 'Not Started', color: '', is_system: true },
  { id: TaskStatus.IN_PROGRESS, name: 'In Progress', color: '', is_system: true },
  { id: TaskStatus.SUBMITTED, name: 'Submitted', color: '', is_system: true },
  { id: TaskStatus.APPROVED, name: 'Approved', color: '', is_system: true },
  { id: TaskStatus.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>
