<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ArrowLeft, Edit2, Save, Trash2, X, CheckCircle2, ShieldAlert, Clock3 } from '@lucide/vue'
import type { TaskState } from '../types'
import { apiFetch } from '../services/api'

interface Project {
  id: string
  name: string
  description: string
  status: string
  progress: number
  updatedAt: string
}

interface Task {
  id: string
  title: string
  state: TaskState
  priority: string
  projectId?: string | null
  updatedAt: string
}

const route = useRoute()
const router = useRouter()
const project = ref<Project | null>(null)
const tasks = ref<Task[]>([])
const loading = ref(true)
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)

async function loadProject() {
  loading.value = true
  error.value = ''
  try {
    const [projectResponse, tasksResponse] = await Promise.all([
      apiFetch(`/api/v1/projects/${projectId.value}`),
      apiFetch('/api/v1/tasks'),
    ])
    if (!projectResponse.ok) throw new Error('Project not found')
    project.value = await projectResponse.json()
    if (tasksResponse.ok) {
      const allTasks: Task[] = await tasksResponse.json()
      tasks.value = allTasks.filter(t => t.projectId === projectId.value || t.projectId === null)
    }
  } catch (e) {
    error.value = e instanceof Error ? e.message : 'Failed to load project'
  } finally {
    loading.value = false
  }
}

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 {
    const response = await apiFetch(`/api/v1/projects/${projectId.value}`, {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        name: editName.value.trim() || undefined,
        description: editDescription.value.trim() || undefined,
      }),
    })
    if (!response.ok) throw new Error('Failed to update project')
    project.value = await response.json()
    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 {
    const response = await apiFetch(`/api/v1/projects/${projectId.value}`, {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ status: 'Offline' }),
    })
    if (!response.ok) throw new Error('Failed to archive project')
    project.value = await response.json()
    showArchive.value = false
  } catch (e) {
    error.value = e instanceof Error ? e.message : 'Failed to archive'
  } finally {
    archiving.value = false
  }
}

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

onMounted(loadProject)
</script>

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

    <div v-if="loading" class="loading-state">Loading project...</div>
    <div v-else-if="error" class="error-state">{{ error }}</div>
    <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" />
              <textarea v-model="editDescription" class="edit-textarea" maxlength="1000" rows="2" placeholder="Description"></textarea>
              <div class="edit-actions">
                <button class="btn-save" @click="saveEdit"><Save :size="14" /> Save</button>
                <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 class="btn-icon" @click="startEditing" title="Edit project"><Edit2 :size="16" /></button>
            <button class="btn-icon btn-danger" @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">
          <article v-for="task in tasks" :key="task.id" class="task-item">
            <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>
          </article>
        </div>
      </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 class="btn-cancel" @click="showArchive = false" :disabled="archiving">Cancel</button>
          <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(--border);
  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(--accent), var(--accent-secondary));
  color: #fff;
  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(--border);
  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: rgba(239, 68, 68, 0.1);
  color: rgb(239, 68, 68);
  border-color: rgba(239, 68, 68, 0.3);
}
.edit-input {
  width: 100%;
  padding: 0.5rem 0.75rem;
  background: var(--surface-raised);
  border: 1px solid var(--border);
  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(--border);
  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: #fff;
  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(--border);
  border-radius: 6px;
  font-size: 0.85rem;
  cursor: pointer;
}
.progress-section {
  margin-top: 1.25rem;
  padding-top: 1rem;
  border-top: 1px solid var(--border);
}
.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(--border);
  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(--border);
  border-radius: 8px;
}
.task-icon {
  flex-shrink: 0;
}
.task-icon.done { color: rgb(34, 197, 94); }
.task-icon.blocked { color: rgb(239, 68, 68); }
.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;
}
.loading-state, .error-state {
  padding: 2rem;
  text-align: center;
  color: var(--text-secondary);
}
.error-state {
  color: rgb(239, 68, 68);
}
/* Modal */
.modal-overlay {
  position: fixed;
  inset: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 100;
}
.modal {
  background: var(--surface);
  border: 1px solid var(--border);
  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: rgb(239, 68, 68);
  color: #fff;
  border: none;
  border-radius: 6px;
  font-size: 0.85rem;
  cursor: pointer;
}
.btn-danger:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}
</style>
