<template>
  <AlertDialog :open="open" @update:open="$emit('update:open', $event)">
    <AlertDialogContent>
      <AlertDialogHeader>
        <AlertDialogTitle>Delete Custom Status</AlertDialogTitle>
        <AlertDialogDescription>
          Are you sure you want to delete the status "{{ status?.name }}"?
        </AlertDialogDescription>
      </AlertDialogHeader>

      <!-- Task Count Warning -->
      <div v-if="taskCount > 0" class="space-y-4">
        <div class="p-4 border border-yellow-500 rounded-lg bg-yellow-50 dark:bg-yellow-950/20">
          <div class="flex items-start gap-3">
            <AlertTriangle class="h-5 w-5 text-yellow-600 dark:text-yellow-500 mt-0.5" />
            <div class="flex-1">
              <p class="text-sm font-medium text-yellow-800 dark:text-yellow-200">
                Status In Use
              </p>
              <p class="text-sm text-yellow-700 dark:text-yellow-300 mt-1">
                This status is currently used by {{ taskCount }} task{{ taskCount !== 1 ? 's' : '' }}.
                You must reassign {{ taskCount === 1 ? 'this task' : 'these tasks' }} to another status before deletion.
              </p>
            </div>
          </div>
        </div>

        <!-- Reassignment Dropdown -->
        <div class="space-y-2">
          <Label for="reassign-status">Reassign tasks to:</Label>
          <Select v-model="selectedReassignStatus">
            <SelectTrigger id="reassign-status">
              <SelectValue placeholder="Select a status" />
            </SelectTrigger>
            <SelectContent>
              <!-- System Statuses -->
              <SelectGroup>
                <SelectLabel>System Statuses</SelectLabel>
                <SelectItem
                  v-for="systemStatus in availableSystemStatuses"
                  :key="systemStatus.id"
                  :value="systemStatus.id"
                >
                  <div class="flex items-center gap-2">
                    <div
                      class="w-3 h-3 rounded-full border"
                      :style="{ backgroundColor: systemStatus.color, borderColor: systemStatus.color }"
                    ></div>
                    <span class="capitalize">{{ formatStatusName(systemStatus.name) }}</span>
                  </div>
                </SelectItem>
              </SelectGroup>

              <!-- Custom Statuses -->
              <SelectGroup v-if="availableCustomStatuses.length > 0">
                <SelectLabel>Custom Statuses</SelectLabel>
                <SelectItem
                  v-for="customStatus in availableCustomStatuses"
                  :key="customStatus.id"
                  :value="customStatus.id"
                >
                  <div class="flex items-center gap-2">
                    <div
                      class="w-3 h-3 rounded-full border"
                      :style="{ backgroundColor: customStatus.color, borderColor: customStatus.color }"
                    ></div>
                    <span class="capitalize">{{ formatStatusName(customStatus.name) }}</span>
                  </div>
                </SelectItem>
              </SelectGroup>
            </SelectContent>
          </Select>
        </div>
      </div>

      <!-- No Tasks Warning -->
      <div v-else class="p-4 border rounded-lg bg-muted/50">
        <p class="text-sm text-muted-foreground">
          This status is not currently in use. It will be permanently deleted.
        </p>
      </div>

      <AlertDialogFooter>
        <AlertDialogCancel :disabled="isDeleting">Cancel</AlertDialogCancel>
        <AlertDialogAction
          :disabled="isDeleting || (taskCount > 0 && !selectedReassignStatus)"
          @click="handleDelete"
          class="bg-destructive hover:bg-destructive/90"
        >
          <Loader2 v-if="isDeleting" class="h-4 w-4 mr-2 animate-spin" />
          Delete Status
        </AlertDialogAction>
      </AlertDialogFooter>
    </AlertDialogContent>
  </AlertDialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { AlertTriangle, Loader2 } from 'lucide-vue-next'
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog'
import {
  Select,
  SelectContent,
  SelectGroup,
  SelectItem,
  SelectLabel,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { Label } from '@/components/ui/label'
import { 
  customTaskStatusService,
  type CustomTaskStatus,
  type SystemTaskStatus
} from '@/services/customTaskStatus'
import { useToast } from '@/components/ui/toast/use-toast'

interface Props {
  open: boolean
  projectId: number
  status: CustomTaskStatus | null
  taskCount: number
  systemStatuses: SystemTaskStatus[]
  customStatuses: CustomTaskStatus[]
}

const props = defineProps<Props>()

const emit = defineEmits<{
  'update:open': [value: boolean]
  success: []
}>()

const { toast } = useToast()

// State
const isDeleting = ref(false)
const selectedReassignStatus = ref<string>('')

// Computed
const availableSystemStatuses = computed(() => props.systemStatuses)

const availableCustomStatuses = computed(() => {
  // Filter out the status being deleted
  return props.customStatuses.filter(s => s.id !== props.status?.id)
})

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

// Methods
const handleDelete = async () => {
  if (!props.status) return

  // If status is in use, require reassignment selection
  if (props.taskCount > 0 && !selectedReassignStatus.value) {
    toast({
      title: 'Reassignment Required',
      description: 'Please select a status to reassign tasks to',
      variant: 'destructive'
    })
    return
  }

  try {
    isDeleting.value = true

    await customTaskStatusService.deleteStatus(
      props.projectId,
      props.status.id,
      selectedReassignStatus.value || undefined
    )

    toast({
      title: 'Success',
      description: `Status "${props.status.name}" has been deleted${
        props.taskCount > 0 ? ` and ${props.taskCount} task${props.taskCount !== 1 ? 's' : ''} reassigned` : ''
      }`
    })

    emit('success')
    emit('update:open', false)
  } catch (error: any) {
    console.error('Failed to delete status:', error)
    
    // Handle specific error cases
    const errorDetail = error.response?.data?.detail
    let errorMessage = 'Failed to delete status'
    
    if (typeof errorDetail === 'object' && errorDetail.error) {
      errorMessage = errorDetail.error
    } else if (typeof errorDetail === 'string') {
      errorMessage = errorDetail
    }

    toast({
      title: 'Error',
      description: errorMessage,
      variant: 'destructive'
    })
  } finally {
    isDeleting.value = false
  }
}

// Reset selected status when dialog opens/closes
watch(() => props.open, (newValue) => {
  if (!newValue) {
    selectedReassignStatus.value = ''
  }
})
</script>
