<script setup lang="ts">
import type { OrgOverview, FacetCounts } from '@/api/types'
import FilterBar from './FilterBar.vue'
import SpecList from './SpecList.vue'
import EmptyState from '@/components/common/EmptyState.vue'
import { ref, computed } from 'vue'

const props = defineProps<{
  overview: OrgOverview
  facets: FacetCounts
}>()

const filters = ref({ team: '', status: '', repo: '' })

const filteredReposWithSpecs = computed(() => {
  let repos = props.overview.repos_with_specs
  if (filters.value.repo) {
    repos = repos.filter(r => r.full_name === filters.value.repo)
  }
  if (filters.value.status) {
    repos = repos.map(r => ({
      ...r,
      specs: r.specs.filter(s => s.status === filters.value.status),
    })).filter(r => r.specs.length > 0)
  }
  return repos
})
</script>

<template>
  <div>
    <div class="flex items-center justify-between mb-6">
      <div>
        <h1 class="text-2xl font-bold font-display text-slate-800 dark:text-slate-100">{{ overview.org }}</h1>
        <p class="text-sm text-slate-500 mt-1">
          {{ overview.total_repos }} repo{{ overview.total_repos !== 1 ? 's' : '' }} &middot;
          {{ overview.total_specs }} spec{{ overview.total_specs !== 1 ? 's' : '' }}
          <template v-if="overview.total_docs"> &middot; {{ overview.total_docs }} doc{{ overview.total_docs !== 1 ? 's' : '' }}</template>
        </p>
      </div>
      <div class="flex items-center gap-2">
        <router-link
          :to="`/app/${overview.org}/tasks`"
          class="inline-flex items-center gap-1.5 px-3 py-1.5 text-sm rounded-md border border-border-light dark:border-slate-600 text-slate-700 dark:text-slate-200 hover:bg-slate-100 dark:hover:bg-slate-700 transition-colors"
        >
          <svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M9 12.75 11.25 15 15 9.75M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z" /></svg>
          Tasks
        </router-link>
        <router-link
          :to="`/app/${overview.org}/editor`"
          class="inline-flex items-center gap-1.5 px-3 py-1.5 text-sm rounded-md bg-accent-500 text-white hover:bg-accent-600 transition-colors"
        >
          <svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M12 4.5v15m7.5-7.5h-15" /></svg>
          New Spec
        </router-link>
      </div>
    </div>

    <FilterBar v-model="filters" :facets="facets" />

    <SpecList
      v-if="filteredReposWithSpecs.length > 0 || overview.repos_without_specs.length > 0"
      :repos-with-specs="filteredReposWithSpecs"
      :repos-without-specs="overview.repos_without_specs"
    />
    <EmptyState
      v-else
      heading="No specs found"
      description="Create your first spec to get started with Specwright."
    />
  </div>
</template>
