<template>
  <div class="space-y-6">
    <!-- Action Buttons -->
    <div v-if="canEdit" class="flex justify-end gap-2">
      <Button 
        v-if="!isEditing" 
        @click="startEditing" 
        variant="outline"
      >
        <Edit class="h-4 w-4 mr-2" />
        Edit Specifications
      </Button>
      <Button 
        v-if="isEditing" 
        @click="cancelEditing" 
        variant="outline"
      >
        Cancel
      </Button>
    </div>

    <!-- Loading State -->
    <div v-if="isLoading" class="flex items-center justify-center py-12">
      <div class="flex items-center gap-2">
        <div class="animate-spin rounded-full h-6 w-6 border-b-2 border-primary"></div>
        <span class="text-muted-foreground">Loading technical specifications...</span>
      </div>
    </div>

    <!-- Error State -->
    <div v-else-if="error" class="text-center py-12">
      <AlertCircle class="h-12 w-12 mx-auto text-destructive mb-4" />
      <h3 class="text-lg font-semibold mb-2">Failed to load specifications</h3>
      <p class="text-muted-foreground mb-4">{{ error }}</p>
      <Button @click="loadSpecs" variant="outline">
        <RefreshCw class="h-4 w-4 mr-2" />
        Try Again
      </Button>
    </div>

    <!-- Edit Mode -->
    <TechnicalSpecsForm
      v-else-if="isEditing"
      :project-id="projectId"
      :initial-specs="specs"
      @saved="onSpecsSaved"
      @cancel="cancelEditing"
    />

    <!-- Display Mode -->
    <TechnicalSpecsDisplay
      v-else
      :specs="specs"
      :user-department="userDepartment"
      :can-edit="canEdit"
      @edit="startEditing"
    />

    <!-- Notification System Integration -->
    <div v-if="showNotification" class="fixed bottom-4 right-4 z-50">
      <Card class="p-4 shadow-lg border-primary">
        <div class="flex items-center gap-3">
          <Bell class="h-5 w-5 text-primary" />
          <div>
            <p class="font-medium">Technical Specifications Updated</p>
            <p class="text-sm text-muted-foreground">Project requirements have been updated</p>
          </div>
          <Button 
            variant="ghost" 
            size="sm" 
            @click="showNotification = false"
          >
            <X class="h-4 w-4" />
          </Button>
        </div>
      </Card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { Edit, AlertCircle, RefreshCw, Bell, X } from 'lucide-vue-next'
import { Button } from '@/components/ui/button'
import { Card } from '@/components/ui/card'
import { useAuthStore } from '@/stores/auth'
import { useToast } from '@/components/ui/toast/use-toast'
import { projectService, type ProjectTechnicalSpecs } from '@/services/project'
import { notificationService } from '@/services/notifications'
import TechnicalSpecsForm from './TechnicalSpecsForm.vue'
import TechnicalSpecsDisplay from './TechnicalSpecsDisplay.vue'

interface Props {
  projectId: number
  userDepartment?: string
}

const props = defineProps<Props>()

const authStore = useAuthStore()
const { toast } = useToast()

// State
const isLoading = ref(false)
const error = ref<string | null>(null)
const specs = ref<ProjectTechnicalSpecs | undefined>()
const isEditing = ref(false)
const showNotification = ref(false)

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

// 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 = err instanceof Error ? err.message : 'Failed to load technical specifications'
  } finally {
    isLoading.value = false
  }
}

const startEditing = () => {
  isEditing.value = true
}

const cancelEditing = () => {
  isEditing.value = false
}

const onSpecsSaved = (updatedSpecs: ProjectTechnicalSpecs) => {
  specs.value = updatedSpecs
  isEditing.value = false
  
  // Show notification
  showNotification.value = true
  setTimeout(() => {
    showNotification.value = false
  }, 5000)
  
  // Notify project members through notification service
  notificationService.notifyProjectMembers(
    props.projectId, 
    'Technical specifications have been updated. Please review the new requirements.'
  )
  
  // Emit notification event for other components
  window.dispatchEvent(new CustomEvent('technical-specs-updated', {
    detail: { projectId: props.projectId, specs: updatedSpecs }
  }))
}

// Lifecycle
onMounted(() => {
  loadSpecs()
})
</script>