<template>
  <Collapsible :open="isOpen" @update:open="isOpen = $event" class="w-full">
    <CollapsibleTrigger asChild>
      <Button variant="ghost" class="flex w-full justify-between p-4 h-auto">
        <div class="flex items-center gap-2">
          <Settings class="h-4 w-4" />
          <span class="font-medium">Technical Specifications</span>
          <Badge v-if="hasSpecs" variant="outline" class="ml-2">
            {{ specsCount }} configured
          </Badge>
        </div>
        <ChevronDown 
          class="h-4 w-4 transition-transform duration-200" 
          :class="{ 'transform rotate-180': isOpen }"
        />
      </Button>
    </CollapsibleTrigger>
    
    <CollapsibleContent class="px-4 pb-4">
      <div v-if="isLoading" class="flex items-center justify-center py-8">
        <div class="animate-spin rounded-full h-6 w-6 border-b-2 border-primary"></div>
      </div>
      
      <div v-else-if="error" class="text-center py-4">
        <AlertCircle class="h-6 w-6 mx-auto text-destructive mb-2" />
        <p class="text-sm text-muted-foreground">{{ error }}</p>
        <Button @click="loadSpecs" variant="outline" size="sm" class="mt-2">
          <RefreshCw class="h-4 w-4 mr-2" />
          Retry
        </Button>
      </div>
      
      <div v-else class="space-y-4">
        <TechnicalSpecsDisplay
          :specs="specs"
          :user-department="userDepartment"
          :can-edit="canEdit"
          @edit="$emit('edit')"
        />
        
        <!-- Separate Department Panel for Better Visibility -->
        <DepartmentSpecsPanel 
          v-if="userDepartment && specs" 
          :department="userDepartment" 
          :project-specs="specs"
        />
      </div>
    </CollapsibleContent>
  </Collapsible>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { Settings, ChevronDown, AlertCircle, RefreshCw } from 'lucide-vue-next'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible'
import { useAuthStore } from '@/stores/auth'
import { projectService, type ProjectTechnicalSpecs } from '@/services/project'
import TechnicalSpecsDisplay from './TechnicalSpecsDisplay.vue'
import DepartmentSpecsPanel from './DepartmentSpecsPanel.vue'

interface Props {
  projectId: number
  userDepartment?: string
  defaultOpen?: boolean
}

interface Emits {
  (e: 'edit'): void
}

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

const authStore = useAuthStore()

// State
const isOpen = ref(props.defaultOpen || false)
const isLoading = ref(false)
const error = ref<string | null>(null)
const specs = ref<ProjectTechnicalSpecs | undefined>()

// Computed properties
const canEdit = computed(() => {
  const userRole = authStore.userRole
  const isAdmin = authStore.user?.is_admin
  return userRole === 'coordinator' || isAdmin
})

const hasSpecs = computed(() => {
  if (!specs.value) return false
  
  const hasBasicSpecs = !!(
    specs.value.frame_rate ||
    specs.value.data_drive_path ||
    specs.value.publish_storage_path ||
    specs.value.delivery_image_resolution
  )
  
  const hasMovieSpecs = !!(
    specs.value.delivery_movie_specs_by_department &&
    Object.keys(specs.value.delivery_movie_specs_by_department).length > 0
  )
  
  return hasBasicSpecs || hasMovieSpecs
})

const specsCount = computed(() => {
  if (!specs.value) return 0
  
  let count = 0
  if (specs.value.frame_rate) count++
  if (specs.value.data_drive_path) count++
  if (specs.value.publish_storage_path) count++
  if (specs.value.delivery_image_resolution) count++
  if (specs.value.delivery_movie_specs_by_department) {
    count += Object.keys(specs.value.delivery_movie_specs_by_department).length
  }
  
  return count
})

// Methods
const loadSpecs = async () => {
  try {
    isLoading.value = true
    error.value = null
    specs.value = await projectService.getProjectTechnicalSpecs(props.projectId)
  } catch (err) {
    console.error('Failed to load technical specifications:', err)
    error.value = 'Failed to load technical specifications'
  } finally {
    isLoading.value = false
  }
}

// Load specs when component mounts or project changes
onMounted(() => {
  loadSpecs()
})

watch(() => props.projectId, () => {
  loadSpecs()
})
</script>