<template>
  <Dialog :open="open" @update:open="handleOpenChange">
    <DialogContent class="sm:max-w-md">
      <DialogHeader>
        <DialogTitle>{{ isEditMode ? 'Edit Status' : 'Add Status' }}</DialogTitle>
        <DialogDescription>
          {{ isEditMode ? 'Update the status name and color' : 'Create a new custom task status' }}
        </DialogDescription>
      </DialogHeader>
      
      <form @submit.prevent="handleSubmit" class="space-y-4">
        <!-- Status Name Input -->
        <div class="space-y-2">
          <Label for="status_name">Status Name</Label>
          <Input
            id="status_name"
            v-model="formData.name"
            placeholder="e.g., In Review, Waiting for Approval"
            required
            maxlength="50"
            @input="validateName"
          />
          <p v-if="nameError" class="text-sm text-destructive">{{ nameError }}</p>
          <p class="text-xs text-muted-foreground">
            {{ formData.name.length }}/50 characters
          </p>
        </div>

        <!-- Color Picker -->
        <div class="space-y-2">
          <Label>Status Color</Label>
          <div class="space-y-3">
            <!-- Predefined Color Palette -->
            <div class="grid grid-cols-5 gap-2">
              <button
                v-for="color in colorPalette"
                :key="color"
                type="button"
                class="w-10 h-10 rounded-md border-2 transition-all hover:scale-110"
                :class="formData.color === color ? 'border-primary ring-2 ring-primary ring-offset-2' : 'border-border'"
                :style="{ backgroundColor: color }"
                @click="selectColor(color)"
                :title="color"
              />
            </div>

            <!-- Custom Color Input -->
            <div class="flex items-center gap-2">
              <Label for="custom_color" class="text-sm">Custom:</Label>
              <Input
                id="custom_color"
                v-model="formData.color"
                type="text"
                placeholder="#000000"
                pattern="^#[0-9A-Fa-f]{6}$"
                maxlength="7"
                class="w-32 font-mono text-sm"
                @input="validateColor"
              />
              <input
                type="color"
                v-model="formData.color"
                class="w-10 h-10 rounded border cursor-pointer"
                title="Pick a color"
              />
            </div>
            <p v-if="colorError" class="text-sm text-destructive">{{ colorError }}</p>
          </div>
        </div>

        <!-- Live Preview -->
        <div class="space-y-2">
          <Label>Preview</Label>
          <div class="flex items-center gap-2 p-3 border rounded-lg bg-muted/30">
            <div
              class="px-3 py-1 rounded-md text-sm font-medium text-white"
              :style="{ backgroundColor: formData.color || '#6B7280' }"
            >
              {{ formData.name || 'Status Name' }}
            </div>
            <span class="text-xs text-muted-foreground">
              This is how the status will appear
            </span>
          </div>
        </div>

        <!-- Set as Default (Edit mode only) -->
        <div v-if="isEditMode" class="flex items-center space-x-2">
          <input
            type="checkbox"
            id="is_default"
            v-model="formData.is_default"
            class="rounded border-gray-300"
          />
          <Label for="is_default" class="text-sm font-normal cursor-pointer">
            Set as default status for new tasks
          </Label>
        </div>

        <!-- Error Message -->
        <div v-if="submitError" class="p-3 border border-destructive rounded-lg bg-destructive/10">
          <p class="text-sm text-destructive">{{ submitError }}</p>
        </div>

        <!-- Actions -->
        <DialogFooter>
          <Button type="button" variant="outline" @click="handleCancel">
            Cancel
          </Button>
          <Button type="submit" :disabled="isSubmitting || !isFormValid">
            <span v-if="isSubmitting" class="flex items-center gap-2">
              <div class="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
              {{ isEditMode ? 'Updating...' : 'Creating...' }}
            </span>
            <span v-else>
              {{ isEditMode ? 'Update Status' : 'Create Status' }}
            </span>
          </Button>
        </DialogFooter>
      </form>
    </DialogContent>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { customTaskStatusService, type CustomTaskStatus } from '@/services/customTaskStatus'
import { useToast } from '@/components/ui/toast/use-toast'

interface Props {
  open: boolean
  projectId: number
  status?: CustomTaskStatus | null
  existingStatusNames?: string[]
}

const props = withDefaults(defineProps<Props>(), {
  status: null,
  existingStatusNames: () => []
})

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

const { toast } = useToast()

// Predefined color palette (matching backend)
const colorPalette = [
  '#8B5CF6', // Purple
  '#EC4899', // Pink
  '#14B8A6', // Teal
  '#F97316', // Orange
  '#06B6D4', // Cyan
  '#84CC16', // Lime
  '#A855F7', // Violet
  '#F43F5E', // Rose
  '#22D3EE', // Sky
  '#FACC15', // Yellow
]

// Form state
const formData = ref({
  name: '',
  color: colorPalette[0],
  is_default: false
})

const isSubmitting = ref(false)
const nameError = ref('')
const colorError = ref('')
const submitError = ref('')

// Computed
const isEditMode = computed(() => !!props.status)

const isFormValid = computed(() => {
  return (
    formData.value.name.trim().length > 0 &&
    formData.value.name.trim().length <= 50 &&
    /^#[0-9A-Fa-f]{6}$/.test(formData.value.color) &&
    !nameError.value &&
    !colorError.value
  )
})

// Methods
const selectColor = (color: string) => {
  formData.value.color = color
  colorError.value = ''
}

const validateName = () => {
  const name = formData.value.name.trim()
  nameError.value = ''
  
  if (!name) {
    nameError.value = 'Status name is required'
    return
  }
  
  if (name.length > 50) {
    nameError.value = 'Status name must be 50 characters or less'
    return
  }
  
  // Check for duplicate names (case-insensitive)
  const isDuplicate = props.existingStatusNames.some(
    existingName => 
      existingName.toLowerCase() === name.toLowerCase() &&
      (!isEditMode.value || existingName.toLowerCase() !== props.status?.name.toLowerCase())
  )
  
  if (isDuplicate) {
    nameError.value = 'A status with this name already exists'
  }
}

const validateColor = () => {
  const color = formData.value.color
  colorError.value = ''
  
  if (!color) {
    colorError.value = 'Color is required'
    return
  }
  
  if (!/^#[0-9A-Fa-f]{6}$/.test(color)) {
    colorError.value = 'Color must be a valid hex code (e.g., #FF5733)'
  }
}

const handleSubmit = async () => {
  // Validate before submit
  validateName()
  validateColor()
  
  if (!isFormValid.value) {
    return
  }
  
  try {
    isSubmitting.value = true
    submitError.value = ''
    
    if (isEditMode.value && props.status) {
      // Update existing status
      await customTaskStatusService.updateStatus(
        props.projectId,
        props.status.id,
        {
          name: formData.value.name.trim(),
          color: formData.value.color,
          is_default: formData.value.is_default
        }
      )
      
      toast({
        title: 'Success',
        description: 'Status updated successfully'
      })
    } else {
      // Create new status
      await customTaskStatusService.createStatus(
        props.projectId,
        {
          name: formData.value.name.trim(),
          color: formData.value.color
        }
      )
      
      toast({
        title: 'Success',
        description: 'Status created successfully'
      })
    }
    
    emit('success')
    emit('update:open', false)
  } catch (error: any) {
    console.error('Failed to save status:', error)
    submitError.value = error.response?.data?.detail || 'Failed to save status'
    
    toast({
      title: 'Error',
      description: submitError.value,
      variant: 'destructive'
    })
  } finally {
    isSubmitting.value = false
  }
}

const handleCancel = () => {
  emit('update:open', false)
}

const handleOpenChange = (value: boolean) => {
  if (!value && !isSubmitting.value) {
    emit('update:open', value)
  }
}

const resetForm = () => {
  if (isEditMode.value && props.status) {
    // Pre-fill form with existing status data
    formData.value = {
      name: props.status.name,
      color: props.status.color,
      is_default: props.status.is_default
    }
  } else {
    // Reset to defaults for new status
    formData.value = {
      name: '',
      color: colorPalette[0],
      is_default: false
    }
  }
  
  nameError.value = ''
  colorError.value = ''
  submitError.value = ''
}

// Watch for dialog open/close and status changes
watch(() => props.open, (newValue) => {
  if (newValue) {
    resetForm()
  }
})

watch(() => props.status, () => {
  if (props.open) {
    resetForm()
  }
})
</script>
