<template>
  <div class="flex items-center gap-2">
    <Select v-model="selectedFilter" @update:model-value="handleFilterChange">
      <SelectTrigger class="w-[200px]">
        <SelectValue placeholder="Filter by task status" />
      </SelectTrigger>
      <SelectContent>
        <SelectItem value="all">All Tasks</SelectItem>
        <SelectGroup>
          <SelectLabel>Modeling</SelectLabel>
          <SelectItem 
            v-for="status in allStatuses" 
            :key="`modeling:${status.id}`"
            :value="`modeling:${status.id}`"
          >
            <div class="flex items-center gap-2">
              <TaskStatusBadge :status="status.id as any" />
              <span>Modeling - {{ status.name }}</span>
            </div>
          </SelectItem>
        </SelectGroup>
        <SelectGroup>
          <SelectLabel>Surfacing</SelectLabel>
          <SelectItem 
            v-for="status in allStatuses" 
            :key="`surfacing:${status.id}`"
            :value="`surfacing:${status.id}`"
          >
            <div class="flex items-center gap-2">
              <TaskStatusBadge :status="status as any" />
              <span>Surfacing - {{ status.name }}</span>
            </div>
          </SelectItem>
        </SelectGroup>
        <SelectGroup>
          <SelectLabel>Rigging</SelectLabel>
          <SelectItem 
            v-for="status in allStatuses" 
            :key="`rigging:${status.id}`"
            :value="`rigging:${status.id}`"
          >
            <div class="flex items-center gap-2">
              <TaskStatusBadge :status="status as any" />
              <span>Rigging - {{ status.name }}</span>
            </div>
          </SelectItem>
        </SelectGroup>
      </SelectContent>
    </Select>
    
    <Button 
      v-if="selectedFilter && selectedFilter !== 'all'" 
      variant="ghost" 
      size="sm" 
      @click="clearFilter"
      class="h-8 px-2"
    >
      <X class="h-4 w-4" />
    </Button>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { X } from 'lucide-vue-next'
import { Button } from '@/components/ui/button'
import {
  Select,
  SelectContent,
  SelectGroup,
  SelectItem,
  SelectLabel,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import TaskStatusBadge from '@/components/task/TaskStatusBadge.vue'
import { TaskStatus } from '@/services/asset'
import { customTaskStatusService, type CustomTaskStatus, type SystemTaskStatus } from '@/services/customTaskStatus'
import { useTaskStatusesStore } from '@/stores/taskStatuses'

interface Props {
  projectId?: number
}

interface Emits {
  (e: 'filter-changed', filter: string): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

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

const selectedFilter = ref('all')

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

// System status options (fallback if no project ID)
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 }
]

// Combine system and custom statuses
const allStatuses = computed(() => {
  if (!props.projectId) {
    return defaultStatusOptions
  }
  
  const statusData = taskStatusesStore.getProjectStatuses(props.projectId)
  if (!statusData) {
    return defaultStatusOptions
  }
  
  // Convert system statuses to the format expected by TaskStatusBadge
  const systemStatusList = statusData.system_statuses.map(status => ({
    id: status.id,
    name: status.name,
    color: status.color,
    is_system: status.is_system
  }))
  
  // Convert custom statuses to the format expected by TaskStatusBadge
  const customStatusList = statusData.statuses.map(status => ({
    id: status.id,
    name: status.name,
    color: status.color,
    is_system: false
  }))
  
  return [...systemStatusList, ...customStatusList]
})

// Load custom statuses when component mounts or projectId changes
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 handleFilterChange = (filter: any) => {
  if (!filter) return
  const filterStr = String(filter)
  selectedFilter.value = filterStr
  // Convert "all" to empty string for the API
  const apiFilter = filterStr === 'all' ? '' : filterStr
  emit('filter-changed', apiFilter)
}

const clearFilter = () => {
  selectedFilter.value = 'all'
  emit('filter-changed', '')
}
</script>