<script setup lang="ts">
import { computed, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
  ArrowLeft,
  Bot,
  CheckCircle2,
  Clock3,
  Edit2,
  Save,
  ShieldAlert,
  ShieldQuestion,
  Trash2,
  Workflow,
  X,
} from '@lucide/vue'
import { useProject, useProjectTasks } from '../api/projects'
import { useOpenClawRuns } from '../api/openClawRuns'
import type { EntityRefDto } from '../api/contracts'
import EntityLink from '../components/mission-control/EntityLink.vue'
import AsyncStatePanel from '../components/mission-control/AsyncStatePanel.vue'

const route = useRoute()
const router = useRouter()
const error = ref('')
const editing = ref(false)
const editName = ref('')
const editDescription = ref('')
const showArchive = ref(false)
const archiving = ref(false)

const projectId = computed(() => route.params.id as string)
const projectState = useProject(projectId)
const tasksState = useProjectTasks(projectId)
const runsState = useOpenClawRuns(computed(() => ({
  projectId: projectId.value,
  limit: 50,
})))
const project = computed(() => projectState.query.data.value ?? null)
const tasks = computed(() => tasksState.data.value ?? [])
const runs = computed(() => runsState.data.value?.items ?? [])
const agents = computed<EntityRefDto[]>(() => {
  const refs = new Map<string, EntityRefDto>()
  for (const task of tasks.value) {
    const agentId = task.expectedFrom || (task.isAgentTask ? task.assignedTo : null)
    if (!agentId) continue
    refs.set(agentId.toLocaleLowerCase(), {
      type: 'agent',
      id: agentId,
      label: agentId,
    })
  }
  return [...refs.values()]
})
const loading = computed(() =>
  projectState.query.isLoading.value || tasksState.isLoading.value,
)
const loadError = computed(() =>
  error.value
  || projectState.query.error.value?.message
  || tasksState.error.value?.message
  || '',
)

function startEditing() {
  if (!project.value) return
  editName.value = project.value.name
  editDescription.value = project.value.description
  editing.value = true
}

async function saveEdit() {
  if (!project.value) return
  try {
    await projectState.updateProject({
      name: editName.value.trim() || undefined,
      description: editDescription.value.trim() || undefined,
    })
    editing.value = false
  } catch (e) {
    error.value = e instanceof Error ? e.message : 'Failed to save'
  }
}

function cancelEdit() {
  editing.value = false
}

async function archiveProject() {
  if (!project.value) return
  archiving.value = true
  try {
    await projectState.updateProject({ status: 'Offline' })
    showArchive.value = false
  } catch (e) {
    error.value = e instanceof Error ? e.message : 'Failed to archive'
  } finally {
    archiving.value = false
  }
}

function getTaskStateIcon(state: string) {
  if (state === 'Done') return CheckCircle2
  if (state === 'Blocked') return ShieldAlert
  return Clock3
}

</script>

<template>
  <div class="project-detail nexus-page nexus-page--reading">
    <header class="detail-header">
      <button type="button" class="back-btn" @click="router.push('/projects')">
        <ArrowLeft :size="17" />
        Back to Projects
      </button>
    </header>

    <AsyncStatePanel
      v-if="loading && !project"
      state="loading"
      title="Projekt wird geladen"
    />
    <AsyncStatePanel
      v-else-if="loadError && !project"
      state="error"
      title="Projekt konnte nicht geladen werden"
      :message="loadError"
      action-label="Erneut versuchen"
      @action="projectState.query.refetch()"
    />
    <template v-else-if="project">
      <div class="project-detail-card">
        <div class="project-detail-top">
          <div class="project-letter-lg">{{ project.name[0] }}</div>
          <div class="project-detail-info">
            <template v-if="editing">
              <input v-model="editName" class="edit-input" maxlength="160" aria-label="Project name" />
              <textarea v-model="editDescription" class="edit-textarea" maxlength="1000" rows="2" aria-label="Project description" placeholder="Description"></textarea>
              <div class="edit-actions">
                <button type="button" class="btn-save" @click="saveEdit"><Save :size="14" /> Save</button>
                <button type="button" class="btn-cancel" @click="cancelEdit"><X :size="14" /> Cancel</button>
              </div>
            </template>
            <template v-else>
              <h1>{{ project.name }}</h1>
              <p class="project-description">{{ project.description || 'No description' }}</p>
              <div class="project-meta">
                <span :class="['badge', project.status === 'Online' || project.status === 'Active' ? 'positive' : 'warning']">{{ project.status }}</span>
                <span class="updated-at">Updated {{ new Date(project.updatedAt).toLocaleString() }}</span>
              </div>
            </template>
          </div>
          <div class="project-detail-actions" v-if="!editing">
            <button type="button" class="btn-icon" aria-label="Edit project" @click="startEditing" title="Edit project"><Edit2 :size="16" /></button>
            <button type="button" class="btn-icon btn-danger" aria-label="Archive project" @click="showArchive = true" title="Archive project"><Trash2 :size="16" /></button>
          </div>
        </div>

        <div class="progress-section">
          <div class="progress-header">
            <span>Progress</span>
            <strong>{{ project.progress }}%</strong>
          </div>
          <div class="progress-bar">
            <i :style="{ width: `${project.progress}%` }"></i>
          </div>
        </div>
      </div>

      <div class="project-tasks-section">
        <h2>Tasks</h2>
        <div v-if="!tasks.length" class="empty-tasks">No tasks associated with this project.</div>
        <div v-else class="task-list">
          <RouterLink
            v-for="task in tasks"
            :key="task.id"
            class="task-item"
            :to="{ name: 'TaskDetail', params: { id: task.id } }"
          >
            <component :is="getTaskStateIcon(task.state)" :size="16" :class="['task-icon', task.state.toLowerCase().replace(' ', '-')]" />
            <div class="task-info">
              <strong>{{ task.title }}</strong>
              <span>{{ task.state }} · {{ task.priority }}</span>
            </div>
            <small>{{ new Date(task.updatedAt).toLocaleDateString() }}</small>
          </RouterLink>
        </div>
      </div>

      <div class="project-relations" aria-label="Linked project results">
        <section class="relation-panel nexus-panel" aria-labelledby="project-agents-title">
          <header>
            <Bot :size="17" aria-hidden="true" />
            <div>
              <span class="eyebrow">TASK ASSIGNMENTS</span>
              <h2 id="project-agents-title">Agents</h2>
            </div>
            <span class="relation-count">{{ agents.length }}</span>
          </header>
          <div v-if="agents.length" class="entity-list">
            <EntityLink
              v-for="agent in agents"
              :key="agent.id"
              :entity="agent"
            />
          </div>
          <p v-else class="relation-empty">
            No task in this project currently supplies an agent assignment.
          </p>
        </section>

        <section class="relation-panel nexus-panel" aria-labelledby="project-runs-title">
          <header>
            <Workflow :size="17" aria-hidden="true" />
            <div>
              <span class="eyebrow">PROJECT FILTER</span>
              <h2 id="project-runs-title">Runs</h2>
            </div>
            <span class="relation-count">{{ runs.length }}</span>
          </header>
          <p v-if="runsState.isPending.value" class="relation-empty" role="status">
            Loading project-linked runs…
          </p>
          <p v-else-if="runsState.error.value" class="relation-empty relation-error" role="alert">
            {{ runsState.error.value instanceof Error ? runsState.error.value.message : 'Runs could not be loaded.' }}
          </p>
          <div v-else-if="runs.length" class="run-list">
            <div v-for="run in runs" :key="run.id" class="run-result">
              <EntityLink
                :entity="{ type: 'run', id: run.id, label: run.title }"
              />
              <span :class="['nexus-status', `run-${run.status.toLocaleLowerCase()}`]">
                {{ run.status }}
              </span>
              <small>{{ new Date(run.updatedAt).toLocaleString() }}</small>
            </div>
          </div>
          <p v-else class="relation-empty">
            No durable Nexus run currently supplies this project ID.
          </p>
        </section>

        <section class="relation-panel nexus-panel relation-panel--wide" aria-labelledby="project-incidents-title">
          <header>
            <ShieldQuestion :size="17" aria-hidden="true" />
            <div>
              <span class="eyebrow">CONTRACT BOUNDARY</span>
              <h2 id="project-incidents-title">Incidents</h2>
            </div>
          </header>
          <p class="relation-empty">
            A project reference is not delivered by the current incident contract.
            Nexus therefore does not infer or fabricate incident links.
          </p>
        </section>
      </div>
    </template>

    <div v-if="showArchive" class="modal-overlay" @click.self="showArchive = false">
      <div class="modal">
        <h3>Archive project?</h3>
        <p>This will set the project status to Archived. Tasks will be preserved but the project will no longer appear in the active list.</p>
        <div class="modal-actions">
          <button type="button" class="btn-cancel" @click="showArchive = false" :disabled="archiving">Cancel</button>
          <button type="button" class="btn-danger" @click="archiveProject" :disabled="archiving">{{ archiving ? 'Archiving...' : 'Archive' }}</button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.project-detail {
  max-width: 800px;
}
.detail-header {
  margin-bottom: 1.25rem;
}
.back-btn {
  display: inline-flex;
  align-items: center;
  gap: 0.4rem;
  background: none;
  border: none;
  color: var(--text-secondary);
  font-size: 0.875rem;
  padding: 0.35rem 0.5rem;
  cursor: pointer;
  border-radius: 6px;
  transition: background 0.15s;
}
.back-btn:hover {
  background: var(--surface-raised);
  color: var(--text-primary);
}
.project-detail-card {
  background: var(--surface);
  border: 1px solid var(--line);
  border-radius: 12px;
  padding: 1.5rem;
}
.project-detail-top {
  display: flex;
  gap: 1rem;
  align-items: flex-start;
}
.project-letter-lg {
  width: 48px;
  height: 48px;
  border-radius: 10px;
  background: linear-gradient(135deg, var(--a-mid), var(--accent-secondary));
  color: var(--tx);
  font-size: 1.25rem;
  font-weight: 600;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}
.project-detail-info {
  flex: 1;
}
.project-detail-info h1 {
  font-size: 1.4rem;
  font-weight: 600;
  margin: 0 0 0.35rem;
  color: var(--text-primary);
}
.project-description {
  font-size: 0.9rem;
  color: var(--text-secondary);
  margin: 0 0 0.75rem;
  line-height: 1.5;
}
.project-meta {
  display: flex;
  align-items: center;
  gap: 0.75rem;
}
.updated-at {
  font-size: 0.8rem;
  color: var(--text-muted);
}
.project-detail-actions {
  display: flex;
  gap: 0.5rem;
}
.btn-icon {
  background: var(--surface-raised);
  border: 1px solid var(--line);
  border-radius: 8px;
  padding: 0.5rem;
  cursor: pointer;
  color: var(--text-secondary);
  display: flex;
  transition: all 0.15s;
}
.btn-icon:hover {
  background: var(--nx-accent-soft);
  color: var(--nx-accent);
}
.btn-icon.btn-danger:hover {
  background: color-mix(in srgb, var(--st-review) 10%, transparent);
  color: var(--st-review);
  border-color: color-mix(in srgb, var(--st-review) 30%, transparent);
}
.edit-input {
  width: 100%;
  padding: 0.5rem 0.75rem;
  background: var(--surface-raised);
  border: 1px solid var(--line);
  border-radius: 8px;
  font-size: 1.1rem;
  color: var(--text-primary);
  margin-bottom: 0.5rem;
}
.edit-textarea {
  width: 100%;
  padding: 0.5rem 0.75rem;
  background: var(--surface-raised);
  border: 1px solid var(--line);
  border-radius: 8px;
  font-size: 0.9rem;
  color: var(--text-primary);
  resize: vertical;
  font-family: inherit;
  margin-bottom: 0.5rem;
}
.edit-actions {
  display: flex;
  gap: 0.5rem;
}
.btn-save {
  display: inline-flex;
  align-items: center;
  gap: 0.35rem;
  padding: 0.4rem 0.8rem;
  background: var(--nx-accent);
  color: var(--tx);
  border: none;
  border-radius: 6px;
  font-size: 0.85rem;
  cursor: pointer;
}
.btn-cancel {
  display: inline-flex;
  align-items: center;
  gap: 0.35rem;
  padding: 0.4rem 0.8rem;
  background: var(--surface-raised);
  color: var(--text-secondary);
  border: 1px solid var(--line);
  border-radius: 6px;
  font-size: 0.85rem;
  cursor: pointer;
}
.progress-section {
  margin-top: 1.25rem;
  padding-top: 1rem;
  border-top: 1px solid var(--line);
}
.progress-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 0.4rem;
  font-size: 0.85rem;
  color: var(--text-secondary);
}
.progress-bar {
  height: 8px;
  background: var(--surface-raised);
  border-radius: 4px;
  overflow: hidden;
}
.progress-bar i {
  display: block;
  height: 100%;
  background: linear-gradient(90deg, var(--nx-accent), var(--accent-secondary));
  border-radius: 4px;
  transition: width 0.3s;
}
.project-tasks-section {
  margin-top: 1.5rem;
}
.project-tasks-section h2 {
  font-size: 1.1rem;
  font-weight: 600;
  margin: 0 0 0.75rem;
  color: var(--text-primary);
}
.empty-tasks {
  color: var(--text-muted);
  font-size: 0.9rem;
  padding: 1.5rem;
  text-align: center;
  background: var(--surface);
  border: 1px dashed var(--line);
  border-radius: 8px;
}
.task-list {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}
.task-item {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  padding: 0.75rem 1rem;
  background: var(--surface);
  border: 1px solid var(--line);
  border-radius: 8px;
  color: inherit;
  text-decoration: none;
  transition: border-color .15s, background .15s;
}
.task-item:hover,
.task-item:focus-visible {
  border-color: color-mix(in srgb, var(--a-mid) 45%, var(--line));
  background: var(--accent-wash);
  outline: none;
}
.task-icon {
  flex-shrink: 0;
}
.task-icon.done { color: var(--st-work); }
.task-icon.blocked { color: var(--st-review); }
.task-icon.backlog { color: var(--text-muted); }
.task-icon.in-progress { color: var(--nx-accent); }
.task-info {
  flex: 1;
}
.task-info strong {
  display: block;
  font-size: 0.9rem;
  color: var(--text-primary);
}
.task-info span {
  font-size: 0.8rem;
  color: var(--text-muted);
}
.task-item small {
  font-size: 0.75rem;
  color: var(--text-muted);
  flex-shrink: 0;
}
.project-relations {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 0.75rem;
  margin-top: 1.5rem;
}
.relation-panel {
  min-width: 0;
  padding: 1rem;
}
.relation-panel--wide {
  grid-column: 1 / -1;
}
.relation-panel > header {
  display: flex;
  align-items: center;
  gap: 0.65rem;
  margin-bottom: 0.8rem;
  color: var(--nx-accent);
}
.relation-panel > header > div {
  flex: 1;
  min-width: 0;
}
.relation-panel h2 {
  margin: 0.1rem 0 0;
  color: var(--text-primary);
  font-size: 1rem;
}
.relation-panel .eyebrow {
  color: var(--text-muted);
  font-size: 0.64rem;
}
.relation-count {
  min-width: 1.7rem;
  padding: 0.2rem 0.45rem;
  color: var(--text-secondary);
  font: 0.7rem/1.2 'JetBrains Mono', monospace;
  text-align: center;
  border: 1px solid var(--line);
  border-radius: 999px;
}
.entity-list {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
}
.run-list {
  display: grid;
  gap: 0.55rem;
}
.run-result {
  display: grid;
  grid-template-columns: minmax(0, 1fr) auto;
  gap: 0.35rem 0.6rem;
  align-items: center;
}
.run-result :deep(.entity-link) {
  min-width: 0;
}
.run-result small {
  grid-column: 1 / -1;
  color: var(--text-muted);
  font: 0.68rem/1.4 'JetBrains Mono', monospace;
}
.relation-empty {
  margin: 0;
  color: var(--text-muted);
  font-size: 0.82rem;
  line-height: 1.5;
}
.relation-error {
  color: var(--st-review);
}
.loading-state, .error-state {
  padding: 2rem;
  text-align: center;
  color: var(--text-secondary);
}
.error-state {
  color: var(--st-review);
}
/* Modal */
.modal-overlay {
  position: fixed;
  inset: 0;
  background: color-mix(in srgb, var(--space-0) 50%, transparent);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 100;
}
.modal {
  background: var(--surface);
  border: 1px solid var(--line);
  border-radius: 12px;
  padding: 1.5rem;
  max-width: 420px;
  width: 90%;
}
.modal h3 {
  margin: 0 0 0.5rem;
  font-size: 1.1rem;
}
.modal p {
  font-size: 0.9rem;
  color: var(--text-secondary);
  margin: 0 0 1rem;
  line-height: 1.5;
}
.modal-actions {
  display: flex;
  gap: 0.5rem;
  justify-content: flex-end;
}
.btn-danger {
  display: inline-flex;
  align-items: center;
  gap: 0.35rem;
  padding: 0.4rem 0.8rem;
  background: var(--st-review);
  color: var(--tx);
  border: none;
  border-radius: 6px;
  font-size: 0.85rem;
  cursor: pointer;
}
.btn-danger:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}
@media (max-width: 700px) {
  .project-relations {
    grid-template-columns: minmax(0, 1fr);
  }
  .relation-panel--wide {
    grid-column: auto;
  }
}
</style>
