<template>
  <form @submit.prevent="handleSubmit" class="space-y-6">
    <!-- Project Context Display -->
    <div v-if="projectContext" class="p-3 bg-muted/50 rounded-md border">
      <div class="flex items-center gap-2 text-sm">
        <div class="font-medium text-muted-foreground">Project:</div>
        <div class="font-semibold">{{ projectContext.name }}</div>
        <div v-if="episodeContext" class="text-muted-foreground">
          • Episode: {{ episodeContext.name }}
        </div>
      </div>
      <div v-if="projectContext.code_name" class="text-xs text-muted-foreground mt-1">
        Code: {{ projectContext.code_name }}
      </div>
    </div>

    <!-- Validation Error Display -->
    <div v-if="validationError" class="p-3 bg-destructive/10 border border-destructive/20 rounded-md">
      <div class="flex items-start gap-2">
        <AlertCircle class="h-4 w-4 text-destructive mt-0.5 flex-shrink-0" />
        <div class="space-y-1">
          <div class="text-sm font-medium text-destructive">{{ validationError.title }}</div>
          <div class="text-sm text-destructive/80">{{ validationError.message }}</div>
          <div v-if="validationError.suggestion" class="text-xs text-muted-foreground">
            {{ validationError.suggestion }}
          </div>
        </div>
      </div>
    </div>

    <!-- Naming Pattern -->
    <div class="space-y-4">
      <div class="space-y-2">
        <Label>Naming Pattern</Label>
        <p class="text-sm text-muted-foreground">
          Configure how shots will be named automatically
          <span v-if="projectContext" class="block mt-1 text-xs">
            All shot names must be unique within project "{{ projectContext.name }}"
          </span>
        </p>
      </div>
      
      <div class="grid grid-cols-2 gap-4">
        <div class="space-y-2">
          <Label for="name_prefix">Name Prefix</Label>
          <Input
            id="name_prefix"
            v-model="formData.name_prefix"
            placeholder="SH"
            :disabled="isLoading"
            :class="validationError?.field === 'name_prefix' ? 'border-destructive focus-visible:ring-destructive' : ''"
            required
          />
        </div>
        <div class="space-y-2">
          <Label for="start_number">Start Number</Label>
          <Input
            id="start_number"
            v-model.number="formData.start_number"
            type="number"
            min="1"
            placeholder="10"
            :disabled="isLoading"
            required
          />
        </div>
      </div>

      <div class="grid grid-cols-2 gap-4">
        <div class="space-y-2">
          <Label for="shot_count">Number of Shots</Label>
          <Input
            id="shot_count"
            v-model.number="formData.shot_count"
            type="number"
            min="1"
            max="1000"
            placeholder="10"
            :disabled="isLoading"
            required
          />
        </div>
        <div class="space-y-2">
          <Label for="number_padding">Number Padding</Label>
          <Select v-model="formData.number_padding" :disabled="isLoading">
            <SelectTrigger>
              <SelectValue placeholder="Select padding" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="2">2 digits (01, 02, 03)</SelectItem>
              <SelectItem value="3">3 digits (010, 020, 030)</SelectItem>
              <SelectItem value="4">4 digits (0010, 0020, 0030)</SelectItem>
            </SelectContent>
          </Select>
        </div>
      </div>

      <!-- Preview -->
      <div class="p-3 bg-muted rounded-md">
        <Label class="text-sm font-medium">Preview:</Label>
        <div class="mt-1 text-sm text-muted-foreground">
          <span v-if="previewNames.length > 0">
            {{ previewNames.slice(0, 3).join(', ') }}
            <span v-if="previewNames.length > 3">... ({{ previewNames.length - 3 }} more)</span>
          </span>
          <span v-else class="italic">Enter values to see preview</span>
        </div>
      </div>
    </div>

    <!-- Frame Range -->
    <div class="space-y-4">
      <div class="space-y-2">
        <Label>Frame Range</Label>
        <p class="text-sm text-muted-foreground">
          Set the default frame range for all shots
        </p>
      </div>
      
      <div class="grid grid-cols-2 gap-4">
        <div class="space-y-2">
          <Label for="frame_start">Start Frame</Label>
          <Input
            id="frame_start"
            v-model.number="formData.frame_start"
            type="number"
            min="1"
            placeholder="1001"
            :disabled="isLoading"
            required
          />
        </div>
        <div class="space-y-2">
          <Label for="frame_end">End Frame</Label>
          <Input
            id="frame_end"
            v-model.number="formData.frame_end"
            type="number"
            min="1"
            placeholder="1100"
            :disabled="isLoading"
            required
          />
        </div>
      </div>

      <!-- Frame Count Display -->
      <div v-if="frameCount > 0" class="text-sm text-muted-foreground">
        Each shot will have {{ frameCount }} frames
      </div>
    </div>

    <!-- Description Template -->
    <div class="space-y-2">
      <Label for="description_template">Description Template (Optional)</Label>
      <Textarea
        id="description_template"
        v-model="formData.description_template"
        placeholder="Shot {shot_name} - {shot_number}"
        :disabled="isLoading"
        rows="2"
      />
      <p class="text-xs text-muted-foreground">
        Use {shot_name} and {shot_number} as placeholders
      </p>
    </div>

    <!-- Task Creation Options -->
    <div class="space-y-4">
      <div class="flex items-center space-x-2">
        <input
          id="create_default_tasks"
          v-model="formData.create_default_tasks"
          type="checkbox"
          class="rounded border-gray-300"
          :disabled="isLoading"
        />
        <Label for="create_default_tasks" class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70">
          Create default tasks for each shot
        </Label>
      </div>
      <p class="text-sm text-muted-foreground ml-6">
        Automatically create layout, animation, lighting, and compositing tasks
      </p>
    </div>

    <!-- Summary -->
    <div class="p-4 bg-muted rounded-md space-y-2">
      <Label class="text-sm font-medium">Summary:</Label>
      <div class="text-sm text-muted-foreground space-y-1">
        <div>• {{ formData.shot_count }} shots will be created</div>
        <div v-if="formData.create_default_tasks">• {{ formData.shot_count * 4 }} tasks will be created (4 per shot)</div>
        <div>• Frame range: {{ formData.frame_start }}-{{ formData.frame_end }} ({{ frameCount }} frames each)</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>
          Creating Shots...
        </div>
        <span v-else>Create {{ formData.shot_count }} Shots</span>
      </Button>
    </div>
  </form>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { AlertCircle } 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 {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import type { BulkShotCreate } from '@/services/shot'
import type { Project } from '@/services/project'
import type { Episode } from '@/services/episode'

interface ValidationErrorDisplay {
  title: string
  message: string
  suggestion?: string
  field?: string
}

interface Props {
  isLoading?: boolean
  projectContext?: Project
  episodeContext?: Episode
  validationError?: ValidationErrorDisplay | null
}

interface Emits {
  (e: 'submit', data: BulkShotCreate): void
  (e: 'cancel'): void
  (e: 'clear-error'): void
}

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

// Form data
const formData = ref({
  name_prefix: 'SH',
  shot_count: 10,
  start_number: 10,
  number_padding: 3,
  frame_start: 1001,
  frame_end: 1100,
  description_template: '',
  create_default_tasks: true
})

// Computed properties
const isFormValid = computed(() => {
  return (
    formData.value.name_prefix.trim() !== '' &&
    formData.value.shot_count > 0 &&
    formData.value.shot_count <= 1000 &&
    formData.value.start_number > 0 &&
    formData.value.frame_start > 0 &&
    formData.value.frame_end > 0 &&
    formData.value.frame_end >= formData.value.frame_start
  )
})

const frameCount = computed(() => {
  if (formData.value.frame_end >= formData.value.frame_start) {
    return formData.value.frame_end - formData.value.frame_start + 1
  }
  return 0
})

const previewNames = computed(() => {
  if (!formData.value.name_prefix || formData.value.shot_count <= 0) {
    return []
  }

  const names = []
  for (let i = 0; i < Math.min(formData.value.shot_count, 10); i++) {
    const shotNumber = formData.value.start_number + i
    const paddedNumber = shotNumber.toString().padStart(formData.value.number_padding, '0')
    names.push(`${formData.value.name_prefix}${paddedNumber}`)
  }
  return names
})

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

  // Clear any existing validation errors
  emit('clear-error')

  const data: BulkShotCreate = {
    name_prefix: formData.value.name_prefix.trim(),
    shot_count: formData.value.shot_count,
    start_number: formData.value.start_number,
    number_padding: formData.value.number_padding,
    frame_start: formData.value.frame_start,
    frame_end: formData.value.frame_end,
    description_template: formData.value.description_template.trim() || undefined,
    create_default_tasks: formData.value.create_default_tasks
  }

  emit('submit', data)
}

// Clear validation error when form data changes
watch(
  () => formData.value.name_prefix,
  () => {
    if (props.validationError?.field === 'name_prefix') {
      emit('clear-error')
    }
  }
)
</script>