<template>
  <form @submit.prevent="handleSubmit" class="space-y-4">
    <!-- 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>

    <!-- Shot Name -->
    <div class="space-y-2">
      <Label for="name">Shot Name</Label>
      <Input
        id="name"
        v-model="formData.name"
        placeholder="Enter shot name (e.g., SH010)"
        :disabled="isLoading"
        :class="validationError?.field === 'name' ? 'border-destructive focus-visible:ring-destructive' : ''"
        required
      />
      <div v-if="projectContext" class="text-xs text-muted-foreground">
        Shot names must be unique within the project "{{ projectContext.name }}"
      </div>
    </div>

    <!-- Frame Range -->
    <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">
      Total frames: {{ frameCount }}
    </div>

    <!-- Shot 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 shot description (optional)"
        :disabled="isLoading"
        rows="3"
      />
    </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 Shot' : 'Create Shot' }}</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 { ShotStatus, type Shot, type ShotCreate, type ShotUpdate, type ProjectValidationError } 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 {
  shot?: Shot
  isLoading?: boolean
  projectContext?: Project
  episodeContext?: Episode
  validationError?: ValidationErrorDisplay | null
}

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

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

// Form data
const formData = ref({
  name: '',
  frame_start: 1001,
  frame_end: 1001,
  status: ShotStatus.NOT_STARTED,
  description: ''
})

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

const isFormValid = computed(() => {
  return (
    formData.value.name.trim() !== '' &&
    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
})

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

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

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

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

  const data = {
    name: formData.value.name.trim(),
    frame_start: formData.value.frame_start,
    frame_end: formData.value.frame_end,
    status: formData.value.status,
    description: formData.value.description.trim() || undefined,
    // Include project_id if available for validation consistency
    project_id: props.projectContext?.id
  }

  emit('submit', data)
}

const resetForm = () => {
  formData.value = {
    name: '',
    frame_start: 1001,
    frame_end: 1001,
    status: ShotStatus.NOT_STARTED,
    description: ''
  }
}

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

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

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