<template>
  <div class="space-y-6">
    <!-- Header -->
    <div>
      <h3 class="text-lg font-semibold">Default Task Templates</h3>
      <p class="text-sm text-muted-foreground mt-1">
        Configure which tasks are automatically created for new assets and shots
      </p>
    </div>

    <!-- Asset Task Templates -->
    <div class="space-y-4">
      <div class="flex items-center gap-2">
        <Package class="h-5 w-5 text-muted-foreground" />
        <h4 class="font-semibold">Asset Task Templates</h4>
      </div>

      <!-- Asset Templates Table -->
      <div class="border rounded-lg overflow-hidden">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead class="w-32">Task Type</TableHead>
              <TableHead class="text-center">Characters</TableHead>
              <TableHead class="text-center">Props</TableHead>
              <TableHead class="text-center">Sets</TableHead>
              <TableHead class="text-center">Vehicles</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            <!-- Dynamic Task Type Rows -->
            <TableRow v-for="taskType in allAssetTaskTypes" :key="taskType">
              <TableCell class="font-medium">
                <div class="flex items-center gap-2">
                  <span class="capitalize">{{ taskType.replace('_', ' ') }}</span>
                  <!-- Edit/Delete icons for custom task types only -->
                  <div v-if="isCustomAssetType(taskType)" class="flex items-center gap-1">
                    <Button
                      variant="ghost"
                      size="icon"
                      class="h-6 w-6"
                      @click="handleEditCustomTaskType(taskType, 'asset')"
                      title="Edit custom task type"
                    >
                      <Pencil class="h-3 w-3" />
                    </Button>
                    <Button
                      variant="ghost"
                      size="icon"
                      class="h-6 w-6"
                      @click="handleDeleteCustomTaskType(taskType, 'asset')"
                      title="Delete custom task type"
                    >
                      <Trash2 class="h-3 w-3" />
                    </Button>
                  </div>
                </div>
              </TableCell>
              <TableCell class="text-center">
                <div class="flex justify-center">
                  <Checkbox
                    :checked="assetTemplates.characters.includes(taskType)"
                    @update:checked="toggleAssetTask('characters', taskType, $event)"
                  />
                </div>
              </TableCell>
              <TableCell class="text-center">
                <div class="flex justify-center">
                  <Checkbox
                    :checked="assetTemplates.props.includes(taskType)"
                    @update:checked="toggleAssetTask('props', taskType, $event)"
                  />
                </div>
              </TableCell>
              <TableCell class="text-center">
                <div class="flex justify-center">
                  <Checkbox
                    :checked="assetTemplates.sets.includes(taskType)"
                    @update:checked="toggleAssetTask('sets', taskType, $event)"
                  />
                </div>
              </TableCell>
              <TableCell class="text-center">
                <div class="flex justify-center">
                  <Checkbox
                    :checked="assetTemplates.vehicles.includes(taskType)"
                    @update:checked="toggleAssetTask('vehicles', taskType, $event)"
                  />
                </div>
              </TableCell>
            </TableRow>
          </TableBody>
        </Table>
      </div>
    </div>

    <Separator />

    <!-- Shot Task Templates -->
    <div class="space-y-4">
      <div class="flex items-center gap-2">
        <Camera class="h-5 w-5 text-muted-foreground" />
        <h4 class="font-semibold">Shot Task Templates</h4>
      </div>

      <!-- Shot Templates Table -->
      <div class="border rounded-lg overflow-hidden">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead class="w-48">Department / Task</TableHead>
              <TableHead class="text-center">Enabled for All Shots</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            <!-- Dynamic Shot Task Type Rows -->
            <TableRow v-for="taskType in allShotTaskTypes" :key="taskType">
              <TableCell class="font-medium">
                <div class="flex items-center gap-2">
                  <span class="capitalize">{{ taskType.replace('_', ' ') }}</span>
                  <!-- Edit/Delete icons for custom task types only -->
                  <div v-if="isCustomShotType(taskType)" class="flex items-center gap-1">
                    <Button
                      variant="ghost"
                      size="icon"
                      class="h-6 w-6"
                      @click="handleEditCustomTaskType(taskType, 'shot')"
                      title="Edit custom task type"
                    >
                      <Pencil class="h-3 w-3" />
                    </Button>
                    <Button
                      variant="ghost"
                      size="icon"
                      class="h-6 w-6"
                      @click="handleDeleteCustomTaskType(taskType, 'shot')"
                      title="Delete custom task type"
                    >
                      <Trash2 class="h-3 w-3" />
                    </Button>
                  </div>
                </div>
              </TableCell>
              <TableCell class="text-center">
                <div class="flex justify-center">
                  <Checkbox
                    :checked="shotTemplates.includes(taskType)"
                    @update:checked="toggleShotTask(taskType, $event)"
                  />
                </div>
              </TableCell>
            </TableRow>
          </TableBody>
        </Table>
      </div>
    </div>

    <!-- Preview Section -->
    <div class="bg-muted/50 rounded-lg p-4 space-y-3">
      <div class="flex items-center gap-2">
        <Info class="h-4 w-4 text-muted-foreground" />
        <span class="text-sm font-medium">Template Preview</span>
      </div>
      <div class="text-sm text-muted-foreground space-y-2">
        <p>
          When creating a new <strong>Character</strong> asset, 
          {{ assetTemplates.characters.length }} task(s) will be created:
          {{ assetTemplates.characters.join(', ') || 'None' }}
        </p>
        <p>
          When creating a new <strong>Shot</strong>, 
          {{ shotTemplates.length }} task(s) will be created:
          {{ shotTemplates.join(', ') || 'None' }}
        </p>
      </div>
    </div>

    <!-- Action Buttons -->
    <div class="flex items-center justify-between pt-4">
      <Button variant="outline" @click="resetToDefaults">
        <RotateCcw class="h-4 w-4 mr-2" />
        Reset to Defaults
      </Button>
      <div class="flex gap-2">
        <Button variant="outline" @click="$emit('cancel')">
          Cancel
        </Button>
        <Button @click="handleSave" :disabled="isSaving">
          <div v-if="isSaving" class="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
          Save Templates
        </Button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, computed } from 'vue'
import { Package, Camera, Info, RotateCcw, Pencil, Trash2 } from 'lucide-vue-next'
import { Button } from '@/components/ui/button'
import { Label } from '@/components/ui/label'
import { Checkbox } from '@/components/ui/checkbox'
import { Separator } from '@/components/ui/separator'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import { customTaskTypeService, type AllTaskTypesResponse } from '@/services/customTaskType'
import { useToast } from '@/components/ui/toast/use-toast'

interface AssetTemplates {
  characters: string[]
  props: string[]
  sets: string[]
  vehicles: string[]
}

interface Props {
  projectId: number
  initialAssetTemplates?: AssetTemplates
  initialShotTemplates?: string[]
  isSaving?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  initialAssetTemplates: () => ({
    characters: ['modeling', 'surfacing', 'rigging'],
    props: ['modeling', 'surfacing'],
    sets: ['modeling', 'surfacing'],
    vehicles: ['modeling', 'surfacing', 'rigging']
  }),
  initialShotTemplates: () => ['layout', 'animation', 'simulation', 'lighting', 'compositing'],
  isSaving: false
})

const emit = defineEmits<{
  save: [data: { assetTemplates: AssetTemplates; shotTemplates: string[] }]
  cancel: []
  editCustomTaskType: [taskType: string, category: 'asset' | 'shot']
  deleteCustomTaskType: [taskType: string, category: 'asset' | 'shot']
}>()

const { toast } = useToast()

// Default templates
const DEFAULT_ASSET_TEMPLATES: AssetTemplates = {
  characters: ['modeling', 'surfacing', 'rigging'],
  props: ['modeling', 'surfacing'],
  sets: ['modeling', 'surfacing'],
  vehicles: ['modeling', 'surfacing', 'rigging']
}

const DEFAULT_SHOT_TEMPLATES = ['layout', 'animation', 'simulation', 'lighting', 'compositing']

// State
const assetTemplates = ref<AssetTemplates>({ ...props.initialAssetTemplates })
const shotTemplates = ref<string[]>([...props.initialShotTemplates])
const taskTypes = ref<AllTaskTypesResponse | null>(null)
const isLoadingTaskTypes = ref(false)

// Computed properties for task types
const allAssetTaskTypes = computed(() => taskTypes.value?.asset_task_types || ['modeling', 'surfacing', 'rigging'])
const allShotTaskTypes = computed(() => taskTypes.value?.shot_task_types || ['layout', 'animation', 'simulation', 'lighting', 'compositing'])
const standardAssetTypes = computed(() => taskTypes.value?.standard_asset_types || ['modeling', 'surfacing', 'rigging'])
const standardShotTypes = computed(() => taskTypes.value?.standard_shot_types || ['layout', 'animation', 'simulation', 'lighting', 'compositing'])
const customAssetTypes = computed(() => taskTypes.value?.custom_asset_types || [])
const customShotTypes = computed(() => taskTypes.value?.custom_shot_types || [])

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

const toggleAssetTask = (category: keyof AssetTemplates, task: string, checked: boolean) => {
  if (checked) {
    if (!assetTemplates.value[category].includes(task)) {
      assetTemplates.value[category].push(task)
    }
  } else {
    assetTemplates.value[category] = assetTemplates.value[category].filter(t => t !== task)
  }
}

const toggleShotTask = (task: string, checked: boolean) => {
  if (checked) {
    if (!shotTemplates.value.includes(task)) {
      shotTemplates.value.push(task)
    }
  } else {
    shotTemplates.value = shotTemplates.value.filter(t => t !== task)
  }
}

const resetToDefaults = () => {
  assetTemplates.value = { ...DEFAULT_ASSET_TEMPLATES }
  shotTemplates.value = [...DEFAULT_SHOT_TEMPLATES]
}

const handleSave = () => {
  emit('save', {
    assetTemplates: assetTemplates.value,
    shotTemplates: shotTemplates.value
  })
}

const isCustomAssetType = (taskType: string) => {
  return customAssetTypes.value.includes(taskType)
}

const isCustomShotType = (taskType: string) => {
  return customShotTypes.value.includes(taskType)
}

const handleEditCustomTaskType = (taskType: string, category: 'asset' | 'shot') => {
  emit('editCustomTaskType', taskType, category)
}

const handleDeleteCustomTaskType = (taskType: string, category: 'asset' | 'shot') => {
  emit('deleteCustomTaskType', taskType, category)
}

// Expose method to refresh task types
const refreshTaskTypes = async () => {
  await loadTaskTypes()
}

defineExpose({
  refreshTaskTypes
})

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

// Watch for prop changes
watch(() => props.initialAssetTemplates, (newVal) => {
  if (newVal) {
    assetTemplates.value = { ...newVal }
  }
}, { deep: true })

watch(() => props.initialShotTemplates, (newVal) => {
  if (newVal) {
    shotTemplates.value = [...newVal]
  }
})
</script>
