<template>
  <div class="space-y-6">
    <!-- Header -->
    <div>
      <h3 class="text-lg font-semibold">Custom Task Types</h3>
      <p class="text-sm text-muted-foreground mt-1">
        Add custom task types beyond the standard types to adapt the pipeline to your project needs
      </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>

    <!-- Content -->
    <div v-else class="space-y-6">
      <!-- Asset Task Types Section -->
      <div class="space-y-4">
        <div class="flex items-center justify-between">
          <div class="flex items-center gap-2">
            <Package class="h-5 w-5 text-muted-foreground" />
            <h4 class="font-semibold">Asset Task Types</h4>
          </div>
          <Button size="sm" @click="openAddDialog('asset')">
            <Plus class="h-4 w-4 mr-2" />
            Add Task Type
          </Button>
        </div>

        <!-- Asset Task Types List -->
        <div class="border rounded-lg divide-y">
          <template v-if="assetTaskTypes.length > 0">
            <div
              v-for="taskType in assetTaskTypes"
              :key="taskType"
              class="flex items-center justify-between p-3 hover:bg-muted/50 transition-colors"
            >
              <div class="flex items-center gap-3">
                <span class="font-medium capitalize">{{ formatTaskTypeName(taskType) }}</span>
                <Badge v-if="isStandardAssetType(taskType)" variant="secondary">
                  Standard
                </Badge>
                <Badge v-else variant="outline">
                  Custom
                </Badge>
              </div>
              <div v-if="!isStandardAssetType(taskType)" class="flex items-center gap-2">
                <Button
                  size="sm"
                  variant="ghost"
                  @click="openEditDialog('asset', taskType)"
                >
                  <Pencil class="h-4 w-4" />
                </Button>
                <Button
                  size="sm"
                  variant="ghost"
                  @click="handleDelete('asset', taskType)"
                >
                  <Trash2 class="h-4 w-4 text-destructive" />
                </Button>
              </div>
            </div>
          </template>
          <div v-else class="p-4 text-center text-sm text-muted-foreground">
            No asset task types defined
          </div>
        </div>
      </div>

      <Separator />

      <!-- Shot Task Types Section -->
      <div class="space-y-4">
        <div class="flex items-center justify-between">
          <div class="flex items-center gap-2">
            <Camera class="h-5 w-5 text-muted-foreground" />
            <h4 class="font-semibold">Shot Task Types</h4>
          </div>
          <Button size="sm" @click="openAddDialog('shot')">
            <Plus class="h-4 w-4 mr-2" />
            Add Task Type
          </Button>
        </div>

        <!-- Shot Task Types List -->
        <div class="border rounded-lg divide-y">
          <template v-if="shotTaskTypes.length > 0">
            <div
              v-for="taskType in shotTaskTypes"
              :key="taskType"
              class="flex items-center justify-between p-3 hover:bg-muted/50 transition-colors"
            >
              <div class="flex items-center gap-3">
                <span class="font-medium capitalize">{{ formatTaskTypeName(taskType) }}</span>
                <Badge v-if="isStandardShotType(taskType)" variant="secondary">
                  Standard
                </Badge>
                <Badge v-else variant="outline">
                  Custom
                </Badge>
              </div>
              <div v-if="!isStandardShotType(taskType)" class="flex items-center gap-2">
                <Button
                  size="sm"
                  variant="ghost"
                  @click="openEditDialog('shot', taskType)"
                >
                  <Pencil class="h-4 w-4" />
                </Button>
                <Button
                  size="sm"
                  variant="ghost"
                  @click="handleDelete('shot', taskType)"
                >
                  <Trash2 class="h-4 w-4 text-destructive" />
                </Button>
              </div>
            </div>
          </template>
          <div v-else class="p-4 text-center text-sm text-muted-foreground">
            No shot task types defined
          </div>
        </div>
      </div>
    </div>

    <!-- Add/Edit Dialog -->
    <Dialog :open="isDialogOpen" @update:open="closeDialog">
      <DialogContent>
        <DialogHeader>
          <DialogTitle>
            {{ dialogMode === 'add' ? 'Add' : 'Edit' }} {{ dialogCategory === 'asset' ? 'Asset' : 'Shot' }} Task Type
          </DialogTitle>
          <DialogDescription>
            {{ dialogMode === 'add' 
              ? 'Enter a name for the new task type. Use lowercase letters, numbers, and underscores only.' 
              : 'Update the task type name. This will update all existing tasks using this type.' 
            }}
          </DialogDescription>
        </DialogHeader>

        <div class="space-y-4 py-4">
          <div class="space-y-2">
            <Label for="taskTypeName">Task Type Name</Label>
            <Input
              id="taskTypeName"
              v-model="taskTypeName"
              placeholder="e.g., grooming, lookdev, previz"
              :class="{ 'border-destructive': validationError }"
              @input="validateTaskTypeName"
            />
            <p v-if="validationError" class="text-sm text-destructive">
              {{ validationError }}
            </p>
            <p v-else class="text-sm text-muted-foreground">
              3-50 characters, lowercase alphanumeric with underscores only
            </p>
          </div>
        </div>

        <DialogFooter>
          <Button variant="outline" @click="closeDialog">
            Cancel
          </Button>
          <Button @click="handleDialogSave" :disabled="!isTaskTypeNameValid || isSaving">
            <div v-if="isSaving" class="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
            {{ dialogMode === 'add' ? 'Add' : 'Update' }}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>

    <!-- Delete Confirmation Dialog -->
    <AlertDialog 
      :open="isDeleteDialogOpen" 
      @update:open="(open) => { 
        isDeleteDialogOpen = open
        if (!open && !isDeleting.value) {
          // Only clear values when dialog closes and we're not in the middle of deleting
          taskTypeToDelete = ''
          categoryToDelete = ''
          deleteError = ''
        }
      }"
    >
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>Delete Task Type</AlertDialogTitle>
          <AlertDialogDescription>
            Are you sure you want to delete the task type "{{ taskTypeToDelete }}"?
            <span v-if="deleteError" class="block mt-2 text-destructive font-medium">
              {{ deleteError }}
            </span>
          </AlertDialogDescription>
        </AlertDialogHeader>
        <AlertDialogFooter>
          <AlertDialogCancel>Cancel</AlertDialogCancel>
          <Button
            @click="confirmDelete"
            :disabled="isDeleting"
            class="bg-destructive hover:bg-destructive/90"
          >
            <div v-if="isDeleting" class="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
            Delete
          </Button>
        </AlertDialogFooter>      </AlertDialogContent>
    </AlertDialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { Package, Camera, Plus, Pencil, Trash2 } from 'lucide-vue-next'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Separator } from '@/components/ui/separator'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog'
import { customTaskTypeService, type AllTaskTypesResponse } from '@/services/customTaskType'
import { useToast } from '@/components/ui/toast/use-toast'

interface Props {
  projectId: number
}

const props = defineProps<Props>()

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

const { toast } = useToast()

// State
const isLoading = ref(true)
const taskTypes = ref<AllTaskTypesResponse | null>(null)

// Dialog state
const isDialogOpen = ref(false)
const dialogMode = ref<'add' | 'edit'>('add')
const dialogCategory = ref<'asset' | 'shot'>('asset')
const taskTypeName = ref('')
const originalTaskTypeName = ref('')
const validationError = ref('')
const isSaving = ref(false)

// Delete dialog state
const isDeleteDialogOpen = ref(false)
const taskTypeToDelete = ref('')
const categoryToDelete = ref<'asset' | 'shot'>('asset')
const deleteError = ref('')
const isDeleting = ref(false)

// Computed
const assetTaskTypes = computed(() => taskTypes.value?.asset_task_types || [])
const shotTaskTypes = computed(() => taskTypes.value?.shot_task_types || [])
const standardAssetTypes = computed(() => taskTypes.value?.standard_asset_types || [])
const standardShotTypes = computed(() => taskTypes.value?.standard_shot_types || [])

const isTaskTypeNameValid = computed(() => {
  return taskTypeName.value.length >= 3 && !validationError.value
})

// Methods
const loadTaskTypes = async () => {
  try {
    isLoading.value = true
    taskTypes.value = await customTaskTypeService.getAllTaskTypes(props.projectId)
  } catch (error: any) {
    console.error('Failed to load task types:', error)
    toast({
      title: 'Error',
      description: error.response?.data?.detail || 'Failed to load task types',
      variant: 'destructive'
    })
  } finally {
    isLoading.value = false
  }
}

const isStandardAssetType = (taskType: string): boolean => {
  return standardAssetTypes.value.includes(taskType)
}

const isStandardShotType = (taskType: string): boolean => {
  return standardShotTypes.value.includes(taskType)
}

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

const validateTaskTypeName = () => {
  const name = taskTypeName.value.trim()
  
  if (name.length === 0) {
    validationError.value = ''
    return
  }
  
  if (name.length < 3) {
    validationError.value = 'Task type name must be at least 3 characters'
    return
  }
  
  if (name.length > 50) {
    validationError.value = 'Task type name must be at most 50 characters'
    return
  }
  
  if (!/^[a-z0-9_]+$/.test(name)) {
    validationError.value = 'Task type name must be lowercase alphanumeric with underscores only'
    return
  }
  
  // Check for duplicates (only if adding or changing name)
  if (dialogMode.value === 'add' || name !== originalTaskTypeName.value) {
    const existingTypes = dialogCategory.value === 'asset' ? assetTaskTypes.value : shotTaskTypes.value
    if (existingTypes.includes(name)) {
      validationError.value = 'A task type with this name already exists'
      return
    }
  }
  
  validationError.value = ''
}

const openAddDialog = (category: 'asset' | 'shot') => {
  dialogMode.value = 'add'
  dialogCategory.value = category
  taskTypeName.value = ''
  originalTaskTypeName.value = ''
  validationError.value = ''
  isDialogOpen.value = true
}

const openEditDialog = (category: 'asset' | 'shot', taskType: string) => {
  dialogMode.value = 'edit'
  dialogCategory.value = category
  taskTypeName.value = taskType
  originalTaskTypeName.value = taskType
  validationError.value = ''
  isDialogOpen.value = true
}

const closeDialog = () => {
  isDialogOpen.value = false
  taskTypeName.value = ''
  originalTaskTypeName.value = ''
  validationError.value = ''
}

const handleDialogSave = async () => {
  validateTaskTypeName()
  
  if (!isTaskTypeNameValid.value) {
    return
  }
  
  try {
    isSaving.value = true
    
    if (dialogMode.value === 'add') {
      const response = await customTaskTypeService.addCustomTaskType(props.projectId, {
        task_type: taskTypeName.value.trim(),
        category: dialogCategory.value
      })
      console.log('Add task type response:', response)
      taskTypes.value = response
      
      toast({
        title: 'Success',
        description: `Task type "${taskTypeName.value}" added successfully`
      })
    } else {
      const response = await customTaskTypeService.updateCustomTaskType(
        props.projectId,
        originalTaskTypeName.value,
        {
          old_name: originalTaskTypeName.value,
          new_name: taskTypeName.value.trim(),
          category: dialogCategory.value
        }
      )
      console.log('Update task type response:', response)
      taskTypes.value = response
      
      toast({
        title: 'Success',
        description: `Task type updated successfully`
      })
    }
    
    emit('updated')
    closeDialog()
  } catch (error: any) {
    console.error('Failed to save task type:', error)
    const errorMessage = error.response?.data?.detail || 'Failed to save task type'
    validationError.value = errorMessage
    toast({
      title: 'Error',
      description: errorMessage,
      variant: 'destructive'
    })
  } finally {
    isSaving.value = false
  }
}

const handleDelete = (category: 'asset' | 'shot', taskType: string) => {
  console.log('=== HANDLE DELETE ===')
  console.log('Received taskType:', taskType)
  console.log('Received category:', category)
  
  taskTypeToDelete.value = taskType
  categoryToDelete.value = category
  deleteError.value = ''
  isDeleteDialogOpen.value = true
  
  console.log('Set taskTypeToDelete.value to:', taskTypeToDelete.value)
  console.log('Set categoryToDelete.value to:', categoryToDelete.value)
}

const closeDeleteDialog = () => {
  console.log('=== CLOSE DELETE DIALOG ===')
  isDeleteDialogOpen.value = false
  // Values will be cleared by @update:open handler
}

const confirmDelete = async () => {
  // Capture values immediately before any async operations
  const taskTypeToDeleteLocal = taskTypeToDelete.value
  const categoryToDeleteLocal = categoryToDelete.value
  
  try {
    isDeleting.value = true
    deleteError.value = ''
    
    console.log('=== DELETE DEBUG ===')
    console.log('taskTypeToDelete.value:', taskTypeToDeleteLocal)
    console.log('categoryToDelete.value:', categoryToDeleteLocal)
    console.log('projectId:', props.projectId)
    
    if (!taskTypeToDeleteLocal) {
      console.error('ERROR: taskTypeToDelete is empty!')
      deleteError.value = 'Task type name is missing. Please try again.'
      isDeleting.value = false
      return
    }
    
    console.log('Deleting task type:', {
      projectId: props.projectId,
      taskType: taskTypeToDeleteLocal,
      category: categoryToDeleteLocal
    })
    
    const response = await customTaskTypeService.deleteCustomTaskType(
      props.projectId,
      taskTypeToDeleteLocal,
      categoryToDeleteLocal
    )
    console.log('Delete task type response:', response)
    taskTypes.value = response
    
    toast({
      title: 'Success',
      description: `Task type "${taskTypeToDeleteLocal}" deleted successfully`
    })
    
    emit('updated')
    
    // Close dialog and clear values
    isDeleteDialogOpen.value = false
    taskTypeToDelete.value = ''
    categoryToDelete.value = ''
    deleteError.value = ''
  } catch (error: any) {
    console.error('Failed to delete task type:', error)
    const errorData = error.response?.data
    
    if (errorData?.task_count) {
      deleteError.value = `Cannot delete: ${errorData.task_count} task(s) are using this type`
    } else {
      deleteError.value = errorData?.detail || 'Failed to delete task type'
    }
    
    toast({
      title: 'Error',
      description: deleteError.value,
      variant: 'destructive'
    })
  } finally {
    isDeleting.value = false
  }
}

// Expose methods for parent component
defineExpose({
  openEditDialog,
  handleDelete
})

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