<template>
  <div class="p-4 sm:p-6">

    <!-- Loading State -->
    <div v-if="isLoadingProject" 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 project...</span>
      </div>
    </div>

    <!-- Error State -->
    <div v-else-if="projectError" 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">Project not found</h3>
      <p class="text-muted-foreground mb-4">{{ projectError }}</p>
      <Button @click="$router.push('/projects')" variant="outline">
        <ArrowLeft class="h-4 w-4 mr-2" />
        Back to Projects
      </Button>
    </div>

    <!-- Main Content -->
    <div v-else>
      <!-- Technical Specifications Manager -->
      <TechnicalSpecsManager 
        :project-id="projectId" 
        :user-department="userDepartment"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { AlertCircle, ArrowLeft } from 'lucide-vue-next'
import { Button } from '@/components/ui/button'
import { useProjectsStore } from '@/stores/projects'
import { useAuthStore } from '@/stores/auth'
import TechnicalSpecsManager from '@/components/project/TechnicalSpecsManager.vue'
import type { Project } from '@/stores/projects'

const route = useRoute()
const router = useRouter()
const projectsStore = useProjectsStore()
const authStore = useAuthStore()

// State
const isLoadingProject = ref(false)
const projectError = ref<string | null>(null)
const project = ref<Project | null>(null)

// Computed properties
const projectId = computed(() => parseInt(route.params.projectId as string))



const userDepartment = computed(() => {
  if (!project.value?.project_members || !authStore.user) return undefined
  
  const member = project.value.project_members.find(m => m.user_id === authStore.user?.id)
  return member?.department_role
})

// Methods
const loadProject = async () => {
  try {
    isLoadingProject.value = true
    projectError.value = null
    
    // Try to get project from store first
    let projectData = projectsStore.getProjectById(projectId.value)
    
    if (!projectData || projectData.id === 0) {
      // Fetch project with members to get user's department role
      projectData = await projectsStore.getProject(projectId.value, true)
    }
    
    if (!projectData || projectData.id === 0) {
      throw new Error('Project not found')
    }
    
    project.value = projectData
  } catch (error) {
    console.error('Failed to load project:', error)
    projectError.value = error instanceof Error ? error.message : 'Failed to load project'
  } finally {
    isLoadingProject.value = false
  }
}

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