<template>
  <div class="space-y-6">
    <!-- Header -->
    <div class="flex items-center justify-between">
      <div>
        <h3 class="text-lg font-semibold">Technical Specifications</h3>
        <p class="text-sm text-muted-foreground">Configure project technical requirements and delivery standards</p>
      </div>
      <Button 
        @click="setDefaults" 
        variant="outline" 
        size="sm"
        :disabled="isLoading"
      >
        <Settings class="h-4 w-4 mr-2" />
        Set Defaults
      </Button>
    </div>

    <form @submit.prevent="onSubmit" class="space-y-6">
      <!-- Basic Technical Settings -->
      <Card>
        <CardHeader>
          <CardTitle class="text-base">Basic Settings</CardTitle>
        </CardHeader>
        <CardContent class="space-y-4">
          <!-- Frame Rate -->
          <div class="grid grid-cols-2 gap-4">
            <div>
              <Label for="frame_rate">Frame Rate (fps)</Label>
              <Select 
                :model-value="formData.frame_rate?.toString()" 
                @update:model-value="formData.frame_rate = parseFloat($event)"
              >
                <SelectTrigger>
                  <SelectValue placeholder="Select frame rate" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem 
                    v-for="rate in COMMON_FRAME_RATES" 
                    :key="rate" 
                    :value="rate.toString()"
                  >
                    {{ FRAME_RATE_LABELS[rate] || `${rate} fps` }}
                  </SelectItem>
                </SelectContent>
              </Select>
            </div>
            
            <!-- Delivery Image Resolution -->
            <div>
              <Label for="delivery_image_resolution">Delivery Image Resolution</Label>
              <Select 
                :model-value="formData.delivery_image_resolution" 
                @update:model-value="formData.delivery_image_resolution = $event"
              >
                <SelectTrigger>
                  <SelectValue placeholder="Select resolution" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem 
                    v-for="resolution in STANDARD_RESOLUTIONS" 
                    :key="resolution" 
                    :value="resolution"
                  >
                    {{ resolution }} ({{ getResolutionLabel(resolution) }})
                  </SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
        </CardContent>
      </Card>

      <!-- Storage Paths -->
      <Card>
        <CardHeader>
          <CardTitle class="text-base">Storage Paths</CardTitle>
        </CardHeader>
        <CardContent class="space-y-4">
          <div>
            <Label for="data_drive_path">Data Drive Path</Label>
            <div class="flex gap-2">
              <Input
                id="data_drive_path"
                v-model="formData.data_drive_path"
                placeholder="e.g., /mnt/projects/data or D:\Projects\Data"
                class="flex-1"
                :class="{ 'border-destructive': getPathValidationMessage(formData.data_drive_path) }"
              />
              <Button type="button" variant="outline" size="sm" title="Browse for folder">
                <FolderOpen class="h-4 w-4" />
              </Button>
            </div>
            <p class="text-xs text-muted-foreground mt-1">Physical path where project work files are stored</p>
            <p v-if="getPathValidationMessage(formData.data_drive_path)" class="text-xs text-destructive mt-1">
              {{ getPathValidationMessage(formData.data_drive_path) }}
            </p>
          </div>
          
          <div>
            <Label for="publish_storage_path">Publish Storage Path</Label>
            <div class="flex gap-2">
              <Input
                id="publish_storage_path"
                v-model="formData.publish_storage_path"
                placeholder="e.g., /mnt/projects/publish or D:\Projects\Publish"
                class="flex-1"
                :class="{ 'border-destructive': getPathValidationMessage(formData.publish_storage_path) }"
              />
              <Button type="button" variant="outline" size="sm" title="Browse for folder">
                <FolderOpen class="h-4 w-4" />
              </Button>
            </div>
            <p class="text-xs text-muted-foreground mt-1">Path where approved work is delivered</p>
            <p v-if="getPathValidationMessage(formData.publish_storage_path)" class="text-xs text-destructive mt-1">
              {{ getPathValidationMessage(formData.publish_storage_path) }}
            </p>
          </div>
        </CardContent>
      </Card>

      <!-- Delivery Movie Specifications -->
      <Card>
        <CardHeader>
          <CardTitle class="text-base">Delivery Movie Specifications by Department</CardTitle>
          <p class="text-sm text-muted-foreground">Configure movie delivery requirements for each department</p>
        </CardHeader>
        <CardContent>
          <div class="space-y-4">
            <div 
              v-for="department in DEPARTMENTS" 
              :key="department"
              class="border rounded-lg p-4 space-y-3"
            >
              <div class="flex items-center justify-between">
                <h4 class="font-medium capitalize">{{ department }}</h4>
                <Badge variant="outline">{{ formatDepartmentName(department) }}</Badge>
              </div>
              
              <div class="grid grid-cols-2 lg:grid-cols-4 gap-3">
                <!-- Resolution -->
                <div>
                  <Label :for="`${department}_resolution`" class="text-xs">Resolution</Label>
                  <Select 
                    :model-value="getMovieSpec(department).resolution" 
                    @update:model-value="updateMovieSpec(department, 'resolution', $event)"
                  >
                    <SelectTrigger class="h-8">
                      <SelectValue placeholder="Resolution" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem 
                        v-for="resolution in STANDARD_RESOLUTIONS" 
                        :key="resolution" 
                        :value="resolution"
                      >
                        {{ resolution }}
                      </SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                
                <!-- Format -->
                <div>
                  <Label :for="`${department}_format`" class="text-xs">Format</Label>
                  <Select 
                    :model-value="getMovieSpec(department).format" 
                    @update:model-value="updateMovieSpec(department, 'format', $event)"
                  >
                    <SelectTrigger class="h-8">
                      <SelectValue placeholder="Format" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem 
                        v-for="format in MOVIE_FORMATS" 
                        :key="format" 
                        :value="format"
                      >
                        {{ format.toUpperCase() }}
                      </SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                
                <!-- Codec -->
                <div>
                  <Label :for="`${department}_codec`" class="text-xs">Codec</Label>
                  <Select 
                    :model-value="getMovieSpec(department).codec || 'none'" 
                    @update:model-value="updateMovieSpec(department, 'codec', $event === 'none' ? undefined : $event)"
                  >
                    <SelectTrigger class="h-8">
                      <SelectValue placeholder="Codec" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="none">None</SelectItem>
                      <SelectItem 
                        v-for="codec in VIDEO_CODECS" 
                        :key="codec" 
                        :value="codec"
                      >
                        {{ codec.toUpperCase() }}
                      </SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                
                <!-- Quality -->
                <div>
                  <Label :for="`${department}_quality`" class="text-xs">Quality</Label>
                  <Select 
                    :model-value="getMovieSpec(department).quality || 'default'" 
                    @update:model-value="updateMovieSpec(department, 'quality', $event === 'default' ? undefined : $event)"
                  >
                    <SelectTrigger class="h-8">
                      <SelectValue placeholder="Quality" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="default">Default</SelectItem>
                      <SelectItem 
                        v-for="quality in QUALITY_SETTINGS" 
                        :key="quality" 
                        :value="quality"
                      >
                        {{ quality.charAt(0).toUpperCase() + quality.slice(1) }}
                      </SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>
            </div>
          </div>
        </CardContent>
      </Card>

      <!-- Form Actions -->
      <div class="flex justify-end gap-3">
        <Button type="button" variant="outline" @click="onCancel">
          Cancel
        </Button>
        <Button type="submit" :disabled="isLoading">
          <div v-if="isLoading" class="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
          Save Technical Specifications
        </Button>
      </div>
    </form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { Settings, FolderOpen } from 'lucide-vue-next'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { useToast } from '@/components/ui/toast/use-toast'
import { projectService, type ProjectTechnicalSpecs, type DeliveryMovieSpec } from '@/services/project'

interface Props {
  projectId: number
  initialSpecs?: ProjectTechnicalSpecs
}

interface Emits {
  (e: 'saved', specs: ProjectTechnicalSpecs): void
  (e: 'cancel'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()
const { toast } = useToast()

// Constants - VFX Industry Standard Values
const COMMON_FRAME_RATES = [23.976, 24.0, 25.0, 29.97, 30.0, 50.0, 59.94, 60.0]
const STANDARD_RESOLUTIONS = [
  "1280x720",   // HD 720p
  "1920x1080",  // HD 1080p
  "2048x1080",  // 2K DCI
  "2560x1440",  // QHD
  "3840x2160",  // 4K UHD
  "4096x2160",  // 4K DCI
  "7680x4320",  // 8K UHD
]
const MOVIE_FORMATS = ["mov", "mp4", "exr", "dpx", "tiff", "ari", "r3d"]
const VIDEO_CODECS = ["h264", "h265", "prores", "dnxhd", "dnxhr", "uncompressed", "avid", "cineform"]
const QUALITY_SETTINGS = ["low", "medium", "high", "lossless"]
const DEPARTMENTS = ["layout", "animation", "lighting", "composite", "modeling", "rigging", "surfacing"]

// Frame rate labels for better UX
const FRAME_RATE_LABELS: Record<number, string> = {
  23.976: "23.976 fps (Cinema)",
  24.0: "24 fps (Cinema)",
  25.0: "25 fps (PAL)",
  29.97: "29.97 fps (NTSC)",
  30.0: "30 fps",
  50.0: "50 fps (PAL High)",
  59.94: "59.94 fps (NTSC High)",
  60.0: "60 fps"
}

// State
const isLoading = ref(false)
const formData = reactive<ProjectTechnicalSpecs>({
  frame_rate: undefined,
  data_drive_path: '',
  publish_storage_path: '',
  delivery_image_resolution: '',
  delivery_movie_specs_by_department: {}
})

// Methods
const getResolutionLabel = (resolution: string) => {
  const labels: Record<string, string> = {
    "1280x720": "HD 720p",
    "1920x1080": "HD 1080p",
    "2048x1080": "2K DCI",
    "2560x1440": "QHD",
    "3840x2160": "4K UHD",
    "4096x2160": "4K DCI",
    "7680x4320": "8K UHD"
  }
  return labels[resolution] || resolution
}

const validatePath = (path: string): boolean => {
  if (!path) return true // Optional field
  
  // Basic path validation - check for valid characters and structure
  const windowsPathRegex = /^[a-zA-Z]:\\(?:[^<>:"|?*\r\n]+\\)*[^<>:"|?*\r\n]*$/
  const unixPathRegex = /^\/(?:[^/\0]+\/)*[^/\0]*$/
  const networkPathRegex = /^\\\\[^\\]+\\[^\\]+(?:\\[^\\]*)*$/
  
  return windowsPathRegex.test(path) || unixPathRegex.test(path) || networkPathRegex.test(path)
}

const getPathValidationMessage = (path: string): string => {
  if (!path) return ''
  if (!validatePath(path)) {
    return 'Please enter a valid file path (e.g., /mnt/projects or D:\\Projects)'
  }
  return ''
}

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

const getMovieSpec = (department: string): DeliveryMovieSpec => {
  return formData.delivery_movie_specs_by_department?.[department] || {
    resolution: "1920x1080",
    format: "mov",
    codec: "h264",
    quality: "medium"
  }
}

const updateMovieSpec = (department: string, field: keyof DeliveryMovieSpec, value: string | undefined) => {
  if (!formData.delivery_movie_specs_by_department) {
    formData.delivery_movie_specs_by_department = {}
  }
  
  if (!formData.delivery_movie_specs_by_department[department]) {
    formData.delivery_movie_specs_by_department[department] = {
      resolution: "1920x1080",
      format: "mov",
      codec: "h264",
      quality: "medium"
    }
  }
  
  formData.delivery_movie_specs_by_department[department][field] = value as any
}

const loadSpecs = async () => {
  try {
    isLoading.value = true
    const specs = await projectService.getProjectTechnicalSpecs(props.projectId)
    
    // Update form data
    Object.assign(formData, {
      frame_rate: specs.frame_rate,
      data_drive_path: specs.data_drive_path || '',
      publish_storage_path: specs.publish_storage_path || '',
      delivery_image_resolution: specs.delivery_image_resolution || '',
      delivery_movie_specs_by_department: specs.delivery_movie_specs_by_department || {}
    })
  } catch (error) {
    console.error('Failed to load technical specifications:', error)
    toast({
      title: 'Error',
      description: 'Failed to load technical specifications',
      variant: 'destructive'
    })
  } finally {
    isLoading.value = false
  }
}

const setDefaults = async () => {
  try {
    isLoading.value = true
    const specs = await projectService.setDefaultTechnicalSpecs(props.projectId)
    
    // Update form data with defaults
    Object.assign(formData, specs)
    
    toast({
      title: 'Defaults Applied',
      description: 'Default technical specifications have been applied'
    })
  } catch (error) {
    console.error('Failed to set default specifications:', error)
    toast({
      title: 'Error',
      description: 'Failed to set default specifications',
      variant: 'destructive'
    })
  } finally {
    isLoading.value = false
  }
}

const onSubmit = async () => {
  try {
    isLoading.value = true
    
    // Validate paths before submitting
    const pathErrors = []
    if (formData.data_drive_path && !validatePath(formData.data_drive_path)) {
      pathErrors.push('Data drive path is invalid')
    }
    if (formData.publish_storage_path && !validatePath(formData.publish_storage_path)) {
      pathErrors.push('Publish storage path is invalid')
    }
    
    if (pathErrors.length > 0) {
      toast({
        title: 'Validation Error',
        description: pathErrors.join(', '),
        variant: 'destructive'
      })
      return
    }
    
    // Clean up empty values
    const specsToSave: ProjectTechnicalSpecs = {
      frame_rate: formData.frame_rate,
      data_drive_path: formData.data_drive_path || undefined,
      publish_storage_path: formData.publish_storage_path || undefined,
      delivery_image_resolution: formData.delivery_image_resolution || undefined,
      delivery_movie_specs_by_department: formData.delivery_movie_specs_by_department
    }
    
    const updatedSpecs = await projectService.updateProjectTechnicalSpecs(props.projectId, specsToSave)
    
    toast({
      title: 'Technical Specifications Updated',
      description: 'Project technical specifications have been saved successfully'
    })
    
    emit('saved', updatedSpecs)
  } catch (error) {
    console.error('Failed to save technical specifications:', error)
    toast({
      title: 'Error',
      description: error instanceof Error ? error.message : 'Failed to save technical specifications',
      variant: 'destructive'
    })
  } finally {
    isLoading.value = false
  }
}

const onCancel = () => {
  emit('cancel')
}

// Initialize form data
onMounted(() => {
  if (props.initialSpecs) {
    Object.assign(formData, props.initialSpecs)
  } else {
    loadSpecs()
  }
})
</script>