<template>
  <div class="relative"
  >
    <Select 
      :model-value="currentStatusId" 
      @update:model-value="handleStatusChange"
      :disabled="isUpdating || isLoadingStatuses"
      
    >
      <SelectTrigger class="h-6 w-[130px] font-semibold text-xs"
        :style="{ backgroundColor: currentStatusObject.color }"
      >
        <SelectValue 
          :model-value="currentStatusId"
        >
          <!-- <TaskStatusBadge :status="currentStatusObject"/> -->
          <!-- console.log(currentStatusObject) -->
           
           <!-- currentStatusObject -->
        </SelectValue>
      </SelectTrigger>
      <SelectContent>
        <SelectItem 
          v-for="statusOption in allStatusOptions" 
          :key="statusOption.id" 
          :value="statusOption.id"
        >
          <div class="flex items-center gap-2">
            <!-- Color indicator -->
            <div 
              v-if="statusOption.color"
              class="w-3 h-3 rounded-full border border-border"
              :style="{ backgroundColor: statusOption.color }"
            />
            <TaskStatusBadge :status="statusOption" compact />
          </div>
        </SelectItem>
      </SelectContent>
    </Select>
    
    <!-- Loading indicator -->
    <div 
      v-if="isUpdating || isLoadingStatuses" 
      class="absolute inset-0 bg-background/50 flex items-center justify-center rounded"
    >
      <div class="animate-spin rounded-full h-4 w-4 border-b-2 border-primary"></div>
    </div>
  </div>
</template>

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

interface StatusOption {
  id: string
  name: string
  color?: string
  is_system?: boolean
}

interface Props {
  assetId: number
  taskType: string
  status: TaskStatus | string
  taskId?: number | null
  projectId: number
}

interface Emits {
  (e: 'status-updated', assetId: number, taskType: string, newStatus: string): void
}

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

// Use the shared task statuses store instead of direct API calls
const taskStatusesStore = useTaskStatusesStore()

const isUpdating = ref(false)

// Get loading state from store
const isLoadingStatuses = computed(() => taskStatusesStore.isLoading(props.projectId))

// Get all status options from store
const allStatusOptions = computed(() => taskStatusesStore.getAllStatusOptions(props.projectId))

// Get current status ID (handle both TaskStatus enum and custom status strings)
const currentStatusId = computed(() => {
  if (typeof props.status === 'string') {
    return props.status
  }
  return props.status as string
})

// Get current status object for display using store
const currentStatusObject = computed((): StatusOption => {
  const statusFromStore = taskStatusesStore.getStatusById(props.projectId, currentStatusId.value)
  if (statusFromStore) {
    return {
      id: statusFromStore.id,
      name: statusFromStore.name,
      color: statusFromStore.color,
      is_system: 'is_system' in statusFromStore ? statusFromStore.is_system : false
    }
  }
  
  // Fallback to current status as-is
  return {
    id: currentStatusId.value,
    name: formatStatusName(currentStatusId.value)
  }
})

// Format status name for display
const formatStatusName = (status: string): string => {
  switch (status) {
    case 'not_started':
      return 'Not Started'
    case 'in_progress':
      return 'In Progress'
    case 'submitted':
      return 'Submitted'
    case 'approved':
      return 'Approved'
    case 'retake':
      return 'Retake'
    default:
      // Convert snake_case to Title Case
      return status.split('_').map(word => 
        word.charAt(0).toUpperCase() + word.slice(1)
      ).join(' ')
  }
}

// Fetch custom statuses for the project using store
const fetchStatuses = async () => {
  if (!props.projectId) return
  
  try {
    await taskStatusesStore.fetchProjectStatuses(props.projectId)
  } catch (error) {
    console.error('Failed to fetch task statuses:', error)
  }
}

const handleStatusChange = async (newStatusId: any) => {
  if (!newStatusId || newStatusId === currentStatusId.value) return
  
  const statusId = newStatusId as string
  
  isUpdating.value = true
  
  try {
    let taskId = props.taskId
    
    // If no task exists, create one first
    if (!taskId) {
      const newTask = await taskService.createAssetTask(props.assetId, props.taskType)
      taskId = newTask.task_id
    }
    
    // Update the task status
    if (taskId) {
      await taskService.updateTaskStatus(taskId, statusId as TaskStatus)
      emit('status-updated', props.assetId, props.taskType, statusId)
    }
  } catch (error) {
    console.error('Failed to update task status:', error)
    // Revert the status change by emitting the original status
    // This will cause the parent component to refresh the data
    emit('status-updated', props.assetId, props.taskType, currentStatusId.value)
  } finally {
    isUpdating.value = false
  }
}

// Fetch statuses on mount
onMounted(() => {
  fetchStatuses()
})

// Refetch statuses when projectId changes
watch(() => props.projectId, () => {
  fetchStatuses()
})
</script>