<script setup lang="ts">
import { computed, onMounted, onUnmounted } from 'vue'
import { useRoute } from 'vue-router'
import { useQuery } from '@tanstack/vue-query'
import { useEditorStore } from '@/stores/editor'
import { useAuthStore } from '@/stores/auth'
import { fetchEditorRepos, fetchEditorFile, fetchNewSpecTemplate } from '@/api/editor'
import { ApiError } from '@/api/client'
import Breadcrumb from '@/components/layout/Breadcrumb.vue'
import EditorList from '@/components/editor/EditorList.vue'
import EditorLayout from '@/components/editor/EditorLayout.vue'
import LoadingSpinner from '@/components/common/LoadingSpinner.vue'

const route = useRoute()
const auth = useAuthStore()
const editorStore = useEditorStore()

const org = computed(() => route.params.org as string)
const owner = computed(() => route.params.owner as string | undefined)
const repo = computed(() => route.params.repo as string | undefined)
const path = computed(() => route.params.path as string | undefined)
const isListMode = computed(() => !owner.value || !repo.value)
const isNew = computed(() => route.name === 'editor-new')
const isConfigMode = computed(() => route.name === 'editor-config')

// List mode: fetch repos
const { data: repos, isLoading: reposLoading } = useQuery({
  queryKey: ['editor-repos', org],
  queryFn: () => fetchEditorRepos(org.value),
  enabled: isListMode,
})

// Edit mode: fetch file (spec or config)
const fileFetchPath = computed(() => isConfigMode.value ? 'SPECWRIGHT.yaml' : path.value)
const { isLoading: fileLoading, isError: fileError, error: fileErrorObj } = useQuery({
  queryKey: ['editor-file', org, owner, repo, fileFetchPath],
  queryFn: async () => {
    if (!owner.value || !repo.value || !fileFetchPath.value) return null
    const result = await fetchEditorFile(org.value, owner.value, repo.value, fileFetchPath.value)
    editorStore.loadFile(result.content, result.sha, fileFetchPath.value)
    return result
  },
  enabled: computed(() => !!owner.value && !!repo.value && !!fileFetchPath.value && !isNew.value),
})

// New mode: fetch template
const { isLoading: templateLoading } = useQuery({
  queryKey: ['editor-template', org, owner, repo],
  queryFn: async () => {
    if (!owner.value || !repo.value) return null
    const result = await fetchNewSpecTemplate(org.value, owner.value, repo.value)
    editorStore.loadFile(result.content, '', '')
    return result
  },
  enabled: computed(() => !!owner.value && !!repo.value && isNew.value),
})

const fileErrorMessage = computed(() => {
  if (!fileError.value) return ''
  const err = fileErrorObj.value
  if (err instanceof ApiError) {
    if (err.status === 403) return 'You do not have permission to view this file. Your session may need to be refreshed — try logging out and back in.'
    if (err.status === 404) return 'File not found. It may have been moved or deleted.'
  }
  return err instanceof Error ? err.message : 'Failed to load file.'
})

const breadcrumbs = computed(() => {
  const items: { label: string; to?: string }[] = [{ label: 'Dashboard', to: `/app/${org.value}/` }]
  if (owner.value && repo.value) {
    items.push({ label: `${owner.value}/${repo.value}`, to: `/app/${org.value}/repos/${owner.value}/${repo.value}` })
    if (isConfigMode.value) {
      items.push({ label: 'SPECWRIGHT.yaml' })
    } else {
      items.push({ label: isNew.value ? 'New Spec' : (path.value || 'Editor') })
    }
  } else {
    items.push({ label: 'Editor' })
  }
  return items
})

onMounted(() => {
  if (isNew.value) {
    editorStore.reset()
  }
})

onUnmounted(() => {
  editorStore.reset()
})
</script>

<template>
  <Breadcrumb :items="breadcrumbs" />

  <!-- List mode -->
  <template v-if="isListMode">
    <LoadingSpinner v-if="reposLoading" />
    <EditorList v-else-if="repos" :repos="repos" />
  </template>

  <!-- Edit/New mode -->
  <template v-else>
    <LoadingSpinner v-if="fileLoading || templateLoading" />

    <!-- Error state -->
    <div v-else-if="fileError" class="mt-6 rounded-lg border border-red-300 dark:border-red-700 bg-red-50 dark:bg-red-900/20 p-4">
      <div class="flex items-start gap-3">
        <svg class="h-5 w-5 text-red-500 mt-0.5 shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L4.082 16.5c-.77.833.192 2.5 1.732 2.5z" />
        </svg>
        <div>
          <h3 class="text-sm font-medium text-red-800 dark:text-red-300">Failed to load file</h3>
          <p class="mt-1 text-sm text-red-700 dark:text-red-400">{{ fileErrorMessage }}</p>
        </div>
      </div>
    </div>

    <EditorLayout
      v-else
      :owner="owner!"
      :repo="repo!"
      :is-new="isNew"
      :config-mode="isConfigMode"
    />
  </template>
</template>
