<template>
  <div class="space-y-6">
    <!-- Header -->
    <div>
      <h3 class="text-lg font-semibold">Custom Task Statuses</h3>
      <p class="text-sm text-muted-foreground mt-1">
        Define custom task statuses with colors to match your production workflow
      </p>
    </div>

    <!-- Loading State -->
    <div v-if="isLoading" class="flex items-center justify-center py-8">
      <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
    </div>

    <!-- Error State -->
    <div v-else-if="loadError" class="p-4 border border-destructive rounded-lg bg-destructive/10">
      <p class="text-sm text-destructive">{{ loadError }}</p>
      <Button size="sm" variant="outline" class="mt-2" @click="loadStatuses">
        Try Again
      </Button>
    </div>

    <!-- Content -->
    <div v-else class="space-y-6">
      <!-- System Statuses Section -->
      <div class="space-y-4">
        <div class="flex items-center gap-2">
          <Shield class="h-5 w-5 text-muted-foreground" />
          <h4 class="font-semibold">System Statuses</h4>
        </div>

        <!-- System Statuses List -->
        <div class="border rounded-lg divide-y">
          <div
            v-for="systemStatus in systemStatuses"
            :key="systemStatus.id"
            class="flex items-center justify-between p-3 bg-muted/30"
          >
            <div class="flex items-center gap-3">
              <div
                class="w-4 h-4 rounded-full border-2"
                :style="{ backgroundColor: systemStatus.color, borderColor: systemStatus.color }"
              ></div>
              <span class="font-medium capitalize">{{ formatStatusName(systemStatus.name) }}</span>
              <Badge variant="secondary">
                System
              </Badge>
            </div>
            <div class="text-sm text-muted-foreground">
              {{ getTaskCount(systemStatus.id) }} task{{ getTaskCount(systemStatus.id) !== 1 ? 's' : '' }}
            </div>
          </div>
        </div>
      </div>

      <Separator />

      <!-- Custom Statuses Section -->
      <div class="space-y-4">
        <div class="flex items-center justify-between">
          <div class="flex items-center gap-2">
            <Palette class="h-5 w-5 text-muted-foreground" />
            <h4 class="font-semibold">Custom Statuses</h4>
          </div>
          <Button size="sm" @click="openAddDialog">
            <Plus class="h-4 w-4 mr-2" />
            Add Status
          </Button>
        </div>

        <!-- Custom Statuses List -->
        <div class="border rounded-lg divide-y">
          <template v-if="customStatuses.length > 0">
            <VueDraggableNext
              v-model="customStatuses"
              :animation="200"
              handle=".drag-handle"
              ghost-class="opacity-50"
              @start="onDragStart"
              @end="onDragEnd"
              :disabled="isReordering"
              class="divide-y"
            >
              <div
                v-for="customStatus in customStatuses"
                :key="customStatus.id"
                class="flex items-center justify-between p-3 hover:bg-muted/50 transition-colors"
                :class="{ 'cursor-move': !isReordering, 'opacity-50': isReordering }"
              >
                <div class="flex items-center gap-3">
                  <!-- Drag Handle -->
                  <div 
                    class="drag-handle cursor-grab active:cursor-grabbing text-muted-foreground hover:text-foreground transition-colors"
                    :class="{ 'cursor-not-allowed': isReordering }"
                  >
                    <GripVertical class="h-5 w-5" />
                  </div>
                  
                  <div
                    class="w-4 h-4 rounded-full border-2"
                    :style="{ backgroundColor: customStatus.color, borderColor: customStatus.color }"
                  ></div>
                  <span class="font-medium capitalize">{{ formatStatusName(customStatus.name) }}</span>
                  <Badge v-if="customStatus.is_default" variant="default">
                    <Star class="h-3 w-3 mr-1" />
                    Default
                  </Badge>
                  <Badge v-else variant="outline">
                    Custom
                  </Badge>
                </div>
                <div class="flex items-center gap-4">
                  <span class="text-sm text-muted-foreground">
                    {{ getTaskCount(customStatus.id) }} task{{ getTaskCount(customStatus.id) !== 1 ? 's' : '' }}
                  </span>
                  <div class="flex items-center gap-1">
                    <Button
                      v-if="!customStatus.is_default"
                      size="sm"
                      variant="outline"
                      @click="handleSetAsDefault(customStatus)"
                      :disabled="isReordering || isSettingDefault"
                      title="Set as default status for new tasks"
                    >
                      <Star class="h-4 w-4 mr-1" />
                      Set as Default
                    </Button>
                    <Button
                      size="sm"
                      variant="ghost"
                      @click="openEditDialog(customStatus)"
                      :disabled="isReordering"
                    >
                      <Pencil class="h-4 w-4" />
                    </Button>
                    <Button
                      size="sm"
                      variant="ghost"
                      @click="handleDelete(customStatus)"
                      :disabled="isReordering"
                    >
                      <Trash2 class="h-4 w-4 text-destructive" />
                    </Button>
                  </div>
                </div>
              </div>
            </VueDraggableNext>
          </template>
          <div v-else class="p-4 text-center text-sm text-muted-foreground">
            No custom statuses defined. Click "Add Status" to create one.
          </div>
        </div>
      </div>
    </div>

    <!-- Add/Edit Status Dialog -->
    <CustomTaskStatusDialog
      :open="isDialogOpen"
      @update:open="isDialogOpen = $event"
      :project-id="props.projectId"
      :status="editingStatus"
      :existing-status-names="existingStatusNames"
      @success="handleDialogSuccess"
    />

    <!-- Delete Confirmation Dialog -->
    <CustomTaskStatusDeleteDialog
      :open="isDeleteDialogOpen"
      @update:open="isDeleteDialogOpen = $event"
      :project-id="props.projectId"
      :status="deletingStatus"
      :task-count="deletingStatusTaskCount"
      :system-statuses="systemStatuses"
      :custom-statuses="customStatuses"
      @success="handleDeleteSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { Shield, Palette, Plus, Pencil, Trash2, Star, GripVertical } from 'lucide-vue-next'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Separator } from '@/components/ui/separator'
import { 
  customTaskStatusService, 
  type AllTaskStatusesResponse,
  type CustomTaskStatus
} from '@/services/customTaskStatus'
import { useTaskStatusesStore } from '@/stores/taskStatuses'
import { useToast } from '@/components/ui/toast/use-toast'
import CustomTaskStatusDialog from './CustomTaskStatusDialog.vue'
import CustomTaskStatusDeleteDialog from './CustomTaskStatusDeleteDialog.vue'
import { VueDraggableNext } from 'vue-draggable-next'

interface Props {
  projectId: number
}

const props = defineProps<Props>()

const emit = defineEmits<{
  updated: []
}>()

const { toast } = useToast()

// Use the shared task statuses store to invalidate cache when statuses change
const taskStatusesStore = useTaskStatusesStore()

// State
const isLoading = ref(true)
const loadError = ref('')
const allStatuses = ref<AllTaskStatusesResponse | null>(null)
const taskCounts = ref<Record<string, number>>({})

// Dialog state
const isDialogOpen = ref(false)
const editingStatus = ref<CustomTaskStatus | null>(null)

// Delete dialog state
const isDeleteDialogOpen = ref(false)
const deletingStatus = ref<CustomTaskStatus | null>(null)
const deletingStatusTaskCount = ref(0)

// Drag and drop state
const isDragging = ref(false)
const isReordering = ref(false)

// Set as default state
const isSettingDefault = ref(false)

// Computed
const systemStatuses = computed(() => allStatuses.value?.system_statuses || [])
const customStatuses = computed({
  get: () => allStatuses.value?.statuses || [],
  set: (value) => {
    if (allStatuses.value) {
      allStatuses.value.statuses = value
    }
  }
})

const existingStatusNames = computed(() => {
  const systemNames = systemStatuses.value.map(s => s.name)
  const customNames = customStatuses.value.map(s => s.name)
  return [...systemNames, ...customNames]
})

// Methods
const loadStatuses = async () => {
  try {
    isLoading.value = true
    loadError.value = ''
    allStatuses.value = await customTaskStatusService.getAllStatuses(props.projectId)
    
    // Load task counts for each status
    await loadTaskCounts()
  } catch (error: any) {
    console.error('Failed to load task statuses:', error)
    loadError.value = error.response?.data?.detail || 'Failed to load task statuses'
    toast({
      title: 'Error',
      description: loadError.value,
      variant: 'destructive'
    })
  } finally {
    isLoading.value = false
  }
}

const loadTaskCounts = async () => {
  // For now, initialize with 0 counts
  // This will be populated when we implement the task count API
  const counts: Record<string, number> = {}
  
  // Initialize system status counts
  systemStatuses.value.forEach(status => {
    counts[status.id] = 0
  })
  
  // Initialize custom status counts
  customStatuses.value.forEach(status => {
    counts[status.id] = 0
  })
  
  taskCounts.value = counts
  
  // TODO: Implement actual task count fetching from API
  // This would require a new endpoint like:
  // GET /projects/{project_id}/task-statuses/counts
  // For now, we'll show 0 for all statuses
}

const getTaskCount = (statusId: string): number => {
  return taskCounts.value[statusId] || 0
}

const formatStatusName = (name: string): string => {
  return name.replace(/_/g, ' ')
}

const openAddDialog = () => {
  editingStatus.value = null
  isDialogOpen.value = true
}

const openEditDialog = (customStatus: CustomTaskStatus) => {
  editingStatus.value = customStatus
  isDialogOpen.value = true
}

const handleDialogSuccess = async () => {
  // Invalidate store cache and reload statuses after successful create/update
  taskStatusesStore.invalidateProject(props.projectId)
  await loadStatuses()
  emit('updated')
}

const handleDelete = (customStatus: CustomTaskStatus) => {
  deletingStatus.value = customStatus
  deletingStatusTaskCount.value = getTaskCount(customStatus.id)
  isDeleteDialogOpen.value = true
}

const handleDeleteSuccess = async () => {
  // Invalidate store cache and reload statuses after successful deletion
  taskStatusesStore.invalidateProject(props.projectId)
  await loadStatuses()
  emit('updated')
}

const handleSetAsDefault = async (customStatus: CustomTaskStatus) => {
  try {
    isSettingDefault.value = true
    
    // Update the status to set is_default to true
    await customTaskStatusService.updateStatus(
      props.projectId,
      customStatus.id,
      {
        is_default: true
      }
    )
    
    toast({
      title: 'Success',
      description: `"${customStatus.name}" is now the default status for new tasks`
    })
    
    // Invalidate store cache and reload to get the updated statuses
    taskStatusesStore.invalidateProject(props.projectId)
    await loadStatuses()
    emit('updated')
  } catch (error: any) {
    console.error('Failed to set default status:', error)
    
    toast({
      title: 'Error',
      description: error.response?.data?.detail || 'Failed to set default status',
      variant: 'destructive'
    })
  } finally {
    isSettingDefault.value = false
  }
}

// Drag and drop handlers
const onDragStart = () => {
  isDragging.value = true
}

const onDragEnd = async (event: any) => {
  isDragging.value = false
  
  // Check if order actually changed
  if (event.oldIndex === event.newIndex) {
    return
  }
  
  // Get the new order of status IDs
  const newOrder = customStatuses.value.map(status => status.id)
  
  try {
    isReordering.value = true
    
    // Call the reorder API
    await customTaskStatusService.reorderStatuses(props.projectId, {
      status_ids: newOrder
    })
    
    toast({
      title: 'Success',
      description: 'Status order updated successfully'
    })
    
    // Invalidate store cache and reload to get the updated order from server
    taskStatusesStore.invalidateProject(props.projectId)
    await loadStatuses()
    emit('updated')
  } catch (error: any) {
    console.error('Failed to reorder statuses:', error)
    
    // Reload to revert to server state on error
    await loadStatuses()
    
    toast({
      title: 'Error',
      description: error.response?.data?.detail || 'Failed to reorder statuses',
      variant: 'destructive'
    })
  } finally {
    isReordering.value = false
  }
}

// Lifecycle
onMounted(() => {
  loadStatuses()
})
</script>
