<template>
  <form @submit.prevent="handleSubmit" class="space-y-4">
    <!-- Asset Name -->
    <div class="space-y-2">
      <Label for="name">Asset Name</Label>
      <Input
        id="name"
        v-model="formData.name"
        placeholder="Enter asset name"
        :disabled="isLoading"
        required
      />
    </div>

    <!-- Asset Category -->
    <div class="space-y-2">
      <Label for="category">Category</Label>
      <Select v-model="formData.category" :disabled="isLoading" required>
        <SelectTrigger>
          <SelectValue placeholder="Select category" />
        </SelectTrigger>
        <SelectContent>
          <SelectItem 
            v-for="category in categories" 
            :key="category.value" 
            :value="category.value"
          >
            <div class="flex items-center gap-2">
              <component :is="category.icon" class="h-4 w-4" />
              {{ category.label }}
            </div>
          </SelectItem>
        </SelectContent>
      </Select>
    </div>

    <!-- Asset Status -->
    <div class="space-y-2">
      <Label for="status">Status</Label>
      <Select v-model="formData.status" :disabled="isLoading">
        <SelectTrigger>
          <SelectValue placeholder="Select status" />
        </SelectTrigger>
        <SelectContent>
          <SelectItem 
            v-for="status in statuses" 
            :key="status.value" 
            :value="status.value"
          >
            <div class="flex items-center gap-2">
              <div 
                class="w-2 h-2 rounded-full" 
                :class="getStatusColor(status.value)"
              ></div>
              {{ status.label }}
            </div>
          </SelectItem>
        </SelectContent>
      </Select>
    </div>

    <!-- Description -->
    <div class="space-y-2">
      <Label for="description">Description</Label>
      <Textarea
        id="description"
        v-model="formData.description"
        placeholder="Enter asset description (optional)"
        :disabled="isLoading"
        rows="3"
      />
    </div>

    <!-- Default Tasks Section (only for new assets) -->
    <div v-if="!isEdit" class="space-y-4 border-t pt-4">
      <div class="space-y-2">
        <div class="flex items-center space-x-2">
          <Checkbox 
            id="create-default-tasks"
            v-model:checked="formData.create_default_tasks"
            :disabled="isLoading"
          />
          <Label for="create-default-tasks" class="text-sm font-medium">
            Create default tasks for this asset
          </Label>
        </div>
        <p class="text-sm text-muted-foreground">
          Automatically create standard tasks based on the asset category
        </p>
      </div>

      <!-- Default Tasks Preview -->
      <div v-if="formData.create_default_tasks && formData.category" class="space-y-3">
        <div class="space-y-2">
          <Label class="text-sm font-medium">Default Tasks Preview</Label>
          <p class="text-xs text-muted-foreground">
            The following tasks will be created for {{ getCategoryLabel(formData.category) }} assets:
          </p>
        </div>

        <!-- Task Selection -->
        <div v-if="defaultTasks.length > 0" class="space-y-2">
          <div 
            v-for="taskType in defaultTasks" 
            :key="taskType"
            class="flex items-center space-x-2"
          >
            <Checkbox 
              :id="`task-${taskType}`"
              :checked="selectedTaskTypes.includes(taskType)"
              @update:checked="toggleTaskType(taskType)"
              :disabled="isLoading"
            />
            <Label :for="`task-${taskType}`" class="text-sm">
              {{ formatTaskType(taskType) }}
            </Label>
          </div>
        </div>

        <!-- Loading state for default tasks -->
        <div v-else-if="loadingDefaultTasks" class="flex items-center gap-2 text-sm text-muted-foreground">
          <div class="animate-spin rounded-full h-4 w-4 border-b-2 border-current"></div>
          Loading default tasks...
        </div>
      </div>

      <!-- Confirmation Dialog Preview -->
      <div v-if="formData.create_default_tasks && selectedTaskTypes.length > 0" class="rounded-md bg-muted p-3">
        <div class="text-sm">
          <div class="font-medium mb-1">Tasks to be created:</div>
          <ul class="list-disc list-inside space-y-1 text-muted-foreground">
            <li v-for="taskType in selectedTaskTypes" :key="taskType">
              {{ formData.name }} - {{ formatTaskType(taskType) }}
            </li>
          </ul>
        </div>
      </div>
    </div>

    <!-- Form Actions -->
    <div class="flex justify-end gap-2 pt-4">
      <Button 
        type="button" 
        variant="outline" 
        @click="$emit('cancel')"
        :disabled="isLoading"
      >
        Cancel
      </Button>
      <Button 
        type="submit" 
        :disabled="isLoading || !isFormValid"
      >
        <div v-if="isLoading" class="flex items-center gap-2">
          <div class="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
          {{ isEdit ? 'Updating...' : 'Creating...' }}
        </div>
        <span v-else>{{ isEdit ? 'Update Asset' : 'Create Asset' }}</span>
      </Button>
    </div>

    <!-- Confirmation Dialog -->
    <AssetCreationConfirmDialog
      v-if="pendingSubmissionData"
      v-model:open="showConfirmDialog"
      :asset-data="(pendingSubmissionData as AssetCreate)"
      :task-list="selectedTaskTypes"
      :loading="isLoading"
      @confirm="handleConfirmSubmission"
      @cancel="handleCancelSubmission"
    />
  </form>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { Users, Package, Building, Car } from 'lucide-vue-next'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import { Checkbox } from '@/components/ui/checkbox'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { AssetCategory, AssetStatus, type Asset, type AssetCreate, type AssetUpdate, assetService } from '@/services/asset'
import AssetCreationConfirmDialog from './AssetCreationConfirmDialog.vue'

interface Props {
  asset?: Asset
  isLoading?: boolean
  projectId?: number
}

interface Emits {
  (e: 'submit', data: AssetCreate | AssetUpdate): void
  (e: 'cancel'): void
}

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

// Form data
const formData = ref({
  name: '',
  category: '' as AssetCategory | '',
  status: AssetStatus.NOT_STARTED,
  description: '',
  create_default_tasks: true
})

// Default tasks state
const defaultTasks = ref<string[]>([])
const selectedTaskTypes = ref<string[]>([])
const loadingDefaultTasks = ref(false)

// Computed properties
const isEdit = computed(() => !!props.asset)

const isFormValid = computed(() => {
  return formData.value.name.trim() !== '' && formData.value.category !== ''
})

// Category options with icons
const categories = [
  { value: AssetCategory.CHARACTERS, label: 'Characters', icon: Users },
  { value: AssetCategory.PROPS, label: 'Props', icon: Package },
  { value: AssetCategory.SETS, label: 'Sets', icon: Building },
  { value: AssetCategory.VEHICLES, label: 'Vehicles', icon: Car }
]

// Status options
const statuses = [
  { value: AssetStatus.NOT_STARTED, label: 'Not Started' },
  { value: AssetStatus.IN_PROGRESS, label: 'In Progress' },
  { value: AssetStatus.ON_HOLD, label: 'On Hold' },
  { value: AssetStatus.COMPLETED, label: 'Completed' },
  { value: AssetStatus.APPROVED, label: 'Approved' }
]

// Methods
const getStatusColor = (status: AssetStatus) => {
  switch (status) {
    case AssetStatus.NOT_STARTED:
      return 'bg-gray-400'
    case AssetStatus.IN_PROGRESS:
      return 'bg-blue-500'
    case AssetStatus.ON_HOLD:
      return 'bg-yellow-500'
    case AssetStatus.COMPLETED:
      return 'bg-green-500'
    case AssetStatus.APPROVED:
      return 'bg-emerald-600'
    default:
      return 'bg-gray-400'
  }
}

// Methods
const getCategoryLabel = (category: AssetCategory) => {
  const categoryMap = {
    [AssetCategory.CHARACTERS]: 'Characters',
    [AssetCategory.PROPS]: 'Props',
    [AssetCategory.SETS]: 'Sets',
    [AssetCategory.VEHICLES]: 'Vehicles'
  }
  return categoryMap[category] || category
}

const formatTaskType = (taskType: string) => {
  return taskType.charAt(0).toUpperCase() + taskType.slice(1)
}

const toggleTaskType = (taskType: string) => {
  const index = selectedTaskTypes.value.indexOf(taskType)
  if (index > -1) {
    selectedTaskTypes.value.splice(index, 1)
  } else {
    selectedTaskTypes.value.push(taskType)
  }
}

const loadDefaultTasks = async (category: AssetCategory) => {
  if (!category) return
  
  loadingDefaultTasks.value = true
  try {
    // Pass projectId to get custom task types if available
    const tasks = await assetService.getDefaultTasksForCategory(category, props.projectId)
    defaultTasks.value = tasks
    selectedTaskTypes.value = [...tasks] // Select all by default
  } catch (error) {
    console.error('Failed to load default tasks:', error)
    defaultTasks.value = []
    selectedTaskTypes.value = []
  } finally {
    loadingDefaultTasks.value = false
  }
}

// Confirmation dialog state
const showConfirmDialog = ref(false)
const pendingSubmissionData = ref<AssetCreate | AssetUpdate | null>(null)

const handleSubmit = () => {
  if (!isFormValid.value) return

  const data: AssetCreate | AssetUpdate = {
    name: formData.value.name.trim(),
    category: formData.value.category as AssetCategory,
    status: formData.value.status,
    description: formData.value.description.trim() || undefined
  }

  // Add default task options for new assets
  if (!isEdit.value) {
    (data as AssetCreate).create_default_tasks = formData.value.create_default_tasks
    if (formData.value.create_default_tasks && selectedTaskTypes.value.length > 0) {
      (data as AssetCreate).selected_task_types = selectedTaskTypes.value
    }

    // Show confirmation dialog for new assets with tasks
    if (formData.value.create_default_tasks && selectedTaskTypes.value.length > 0) {
      pendingSubmissionData.value = data
      showConfirmDialog.value = true
      return
    }
  }

  emit('submit', data)
}

const handleConfirmSubmission = () => {
  if (pendingSubmissionData.value) {
    emit('submit', pendingSubmissionData.value)
    showConfirmDialog.value = false
    pendingSubmissionData.value = null
  }
}

const handleCancelSubmission = () => {
  showConfirmDialog.value = false
  pendingSubmissionData.value = null
}

const resetForm = () => {
  formData.value = {
    name: '',
    category: '' as AssetCategory | '',
    status: AssetStatus.NOT_STARTED,
    description: '',
    create_default_tasks: true
  }
  defaultTasks.value = []
  selectedTaskTypes.value = []
}

// Watch for asset changes to populate form
watch(
  () => props.asset,
  (asset) => {
    if (asset) {
      formData.value = {
        name: asset.name,
        category: asset.category,
        status: asset.status,
        description: asset.description || '',
        create_default_tasks: true
      }
    } else {
      resetForm()
    }
  },
  { immediate: true }
)

// Watch for category changes to load default tasks
watch(
  () => formData.value.category,
  (newCategory) => {
    if (newCategory && !isEdit.value) {
      loadDefaultTasks(newCategory as AssetCategory)
    }
  }
)

// Expose reset method
defineExpose({
  resetForm
})
</script>