<template>
  <div class="p-6">
    <!-- Back link + Header -->
    <div class="flex items-center gap-3 mb-6">
      <router-link
        to="/projects"
        class="p-1.5 text-text-tertiary hover:text-text-primary transition-colors rounded-lg focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-accent"
        aria-label="Back to projects"
        v-tooltip="'Back to projects'"
      >
        <ArrowLeft class="w-4 h-4" :stroke-width="2" aria-hidden="true" />
      </router-link>
      <div
        class="w-3 h-3 rounded-full shrink-0"
        :style="{ backgroundColor: project?.color || '#6B7280' }"
        aria-hidden="true"
      />
      <h1 class="text-[1.75rem] font-bold font-[family-name:var(--font-heading)] tracking-tight text-text-primary">
        {{ project?.name || 'Project' }}
      </h1>
      <span
        v-if="project?.archived"
        class="text-[0.625rem] font-medium text-text-tertiary bg-bg-elevated px-2 py-0.5 rounded-full"
      >
        Archived
      </span>
      <div class="ml-auto flex items-center gap-2">
        <button
          @click="$router.push({ path: '/projects', query: { edit: String(project?.id) } })"
          class="px-3 py-1.5 text-[0.75rem] border border-border-subtle text-text-secondary rounded-lg hover:bg-bg-elevated transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-accent"
        >
          Edit Project
        </button>
      </div>
    </div>

    <div v-if="!project" class="flex flex-col items-center justify-center py-16">
      <FolderKanban class="w-12 h-12 text-text-tertiary" :stroke-width="1.5" aria-hidden="true" />
      <p class="text-sm text-text-secondary mt-4">Project not found</p>
      <router-link to="/projects" class="mt-4 px-4 py-2 bg-accent text-bg-base text-xs font-medium rounded-lg hover:bg-accent-hover transition-colors">
        Back to Projects
      </router-link>
    </div>

    <template v-else>
      <!-- Summary Cards -->
      <div class="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
        <div class="bg-bg-surface border border-border-subtle rounded-lg p-4">
          <p class="text-[0.6875rem] text-text-tertiary uppercase tracking-[0.08em] mb-1">Client</p>
          <p class="text-[0.9375rem] font-semibold text-text-primary">{{ clientName }}</p>
        </div>
        <div class="bg-bg-surface border border-border-subtle rounded-lg p-4">
          <p class="text-[0.6875rem] text-text-tertiary uppercase tracking-[0.08em] mb-1">Rate</p>
          <p class="text-[0.9375rem] font-semibold text-text-primary">
            {{ project.budget_amount ? formatCurrency(project.budget_amount) + ' fixed' : formatCurrency(project.hourly_rate) + '/hr' }}
          </p>
        </div>
        <div class="bg-bg-surface border border-border-subtle rounded-lg p-4">
          <p class="text-[0.6875rem] text-text-tertiary uppercase tracking-[0.08em] mb-1">Total Hours</p>
          <p class="text-[0.9375rem] font-semibold text-text-primary">{{ formatNumber(totalHours, 1) }}h</p>
        </div>
        <div class="bg-bg-surface border border-border-subtle rounded-lg p-4">
          <p class="text-[0.6875rem] text-text-tertiary uppercase tracking-[0.08em] mb-1">Revenue</p>
          <p class="text-[0.9375rem] font-semibold text-text-primary">{{ formatCurrency(totalRevenue) }}</p>
        </div>
      </div>

      <!-- Budget Progress -->
      <div v-if="project.budget_hours && budgetData" class="bg-bg-surface border border-border-subtle rounded-lg p-4 mb-6">
        <div class="flex items-center justify-between mb-2">
          <p class="text-[0.8125rem] font-medium text-text-primary">Budget Progress</p>
          <span class="text-[0.75rem]" :class="budgetPct > 90 ? 'text-status-error-text' : budgetPct > 75 ? 'text-status-warning' : 'text-text-secondary'">
            {{ formatNumber(budgetData.hours_used, 1) }}h / {{ project.budget_hours }}h ({{ formatNumber(budgetPct, 0) }}%)
          </span>
        </div>
        <div class="w-full bg-bg-elevated rounded-full h-2" role="progressbar" :aria-valuenow="Math.round(budgetPct)" aria-valuemin="0" aria-valuemax="100" :aria-label="'Budget progress: ' + formatNumber(budgetPct, 0) + '%'">
          <div
            class="h-2 rounded-full transition-all duration-500"
            :class="budgetPct > 90 ? 'bg-status-error' : budgetPct > 75 ? 'bg-status-warning' : 'bg-accent'"
            :style="{ width: Math.min(budgetPct, 100) + '%' }"
          />
        </div>
        <p v-if="budgetData.hours_remaining !== null" class="text-[0.6875rem] text-text-tertiary mt-1.5">
          {{ formatNumber(budgetData.hours_remaining, 1) }}h remaining
          <template v-if="budgetData.pace"> - {{ budgetData.pace === 'ahead' ? 'ahead of schedule' : budgetData.pace === 'on_track' ? 'on track' : budgetData.pace === 'behind' ? 'behind schedule' : budgetData.pace }}</template>
        </p>
      </div>

      <!-- Two-column: Tasks + Notes -->
      <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
        <!-- Tasks / Estimates vs Actuals -->
        <div class="bg-bg-surface border border-border-subtle rounded-lg p-4">
          <h2 class="text-[0.8125rem] font-medium text-text-primary mb-3">Tasks</h2>
          <div v-if="taskActualsData.length > 0" class="space-y-2">
            <div
              v-for="ta in taskActualsData"
              :key="ta.task_id"
              class="flex items-center gap-3 px-3 py-2 bg-bg-inset rounded-lg"
            >
              <span class="text-[0.75rem] text-text-primary truncate flex-1 min-w-0">{{ ta.task_name }}</span>
              <span class="text-[0.6875rem] font-mono text-accent-text shrink-0">{{ formatNumber(ta.actual_hours, 1) }}h</span>
              <template v-if="ta.estimated_hours">
                <span class="text-[0.6875rem] text-text-tertiary shrink-0">of {{ formatNumber(ta.estimated_hours, 1) }}h</span>
                <div class="w-16 bg-bg-elevated rounded-full h-1.5 shrink-0" role="progressbar" :aria-valuenow="Math.round(ta.progress || 0)" aria-valuemin="0" aria-valuemax="100">
                  <div
                    class="h-1.5 rounded-full"
                    :class="(ta.progress || 0) > 100 ? 'bg-status-error' : 'bg-accent'"
                    :style="{ width: Math.min(ta.progress || 0, 100) + '%' }"
                  />
                </div>
              </template>
              <span
                v-if="ta.hourly_rate"
                class="text-[0.625rem] text-text-tertiary shrink-0"
              >{{ formatCurrency(ta.hourly_rate) }}/hr</span>
            </div>
          </div>
          <div v-else-if="tasks.length > 0" class="space-y-1.5">
            <div v-for="task in tasks" :key="task.id" class="flex items-center gap-2 px-3 py-2 bg-bg-inset rounded-lg">
              <span class="text-[0.75rem] text-text-primary truncate flex-1">{{ task.name }}</span>
              <span v-if="task.estimated_hours" class="text-[0.625rem] text-text-tertiary">{{ task.estimated_hours }}h est</span>
            </div>
          </div>
          <p v-else class="text-[0.75rem] text-text-tertiary">No tasks defined for this project.</p>
        </div>

        <!-- Notes -->
        <div class="bg-bg-surface border border-border-subtle rounded-lg p-4">
          <h2 class="text-[0.8125rem] font-medium text-text-primary mb-3">Notes</h2>
          <p v-if="project.notes" class="text-[0.75rem] text-text-secondary whitespace-pre-wrap leading-relaxed">{{ project.notes }}</p>
          <p v-else class="text-[0.75rem] text-text-tertiary">No notes for this project.</p>
        </div>
      </div>

      <!-- Recent Entries -->
      <div class="bg-bg-surface border border-border-subtle rounded-lg p-4 mb-6">
        <div class="flex items-center justify-between mb-3">
          <h2 class="text-[0.8125rem] font-medium text-text-primary">Recent Entries</h2>
          <span class="text-[0.6875rem] text-text-tertiary">{{ projectEntries.length }} entries</span>
        </div>
        <div v-if="projectEntries.length > 0" class="overflow-x-auto">
          <table class="w-full">
            <thead>
              <tr class="border-b border-border-subtle">
                <th class="px-3 py-2 text-left text-[0.6875rem] text-text-tertiary uppercase tracking-[0.08em] font-medium">Date</th>
                <th class="px-3 py-2 text-left text-[0.6875rem] text-text-tertiary uppercase tracking-[0.08em] font-medium">Task</th>
                <th class="px-3 py-2 text-left text-[0.6875rem] text-text-tertiary uppercase tracking-[0.08em] font-medium">Description</th>
                <th class="px-3 py-2 text-right text-[0.6875rem] text-text-tertiary uppercase tracking-[0.08em] font-medium">Duration</th>
              </tr>
            </thead>
            <tbody>
              <tr
                v-for="entry in projectEntries.slice(0, 50)"
                :key="entry.id"
                class="border-b border-border-subtle last:border-0 hover:bg-bg-elevated transition-colors"
              >
                <td class="px-3 py-2 text-[0.75rem] text-text-primary whitespace-nowrap">{{ formatDate(entry.start_time) }}</td>
                <td class="px-3 py-2 text-[0.75rem] text-text-secondary">{{ getTaskName(entry.task_id) || '-' }}</td>
                <td class="px-3 py-2 text-[0.75rem] text-text-secondary truncate max-w-[300px]">{{ entry.description || '-' }}</td>
                <td class="px-3 py-2 text-right text-[0.75rem] font-mono text-accent-text whitespace-nowrap">{{ formatDuration(entry.duration) }}</td>
              </tr>
            </tbody>
          </table>
        </div>
        <p v-else class="text-[0.75rem] text-text-tertiary">No time entries for this project yet.</p>
      </div>

      <!-- Tracked Apps -->
      <div v-if="trackedApps.length > 0" class="bg-bg-surface border border-border-subtle rounded-lg p-4">
        <h2 class="text-[0.8125rem] font-medium text-text-primary mb-3">Tracked Apps</h2>
        <div class="flex flex-wrap gap-2">
          <div
            v-for="app in trackedApps"
            :key="app.id"
            class="flex items-center gap-2 px-3 py-1.5 bg-bg-inset rounded-lg"
          >
            <img v-if="app.icon" :src="app.icon" class="w-4 h-4 shrink-0" alt="" />
            <div v-else class="w-4 h-4 shrink-0 rounded bg-bg-elevated" />
            <span class="text-[0.75rem] text-text-primary">{{ app.display_name || app.exe_name }}</span>
          </div>
        </div>
      </div>
    </template>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { ArrowLeft, FolderKanban } from 'lucide-vue-next'
import { invoke } from '@tauri-apps/api/core'
import { useProjectsStore, type Project, type Task } from '../stores/projects'
import { useClientsStore } from '../stores/clients'
import { formatCurrency, formatNumber, formatDate } from '../utils/locale'

const route = useRoute()
const projectsStore = useProjectsStore()
const clientsStore = useClientsStore()

const project = ref<Project | null>(null)
const tasks = ref<Task[]>([])
const projectEntries = ref<Array<{ id: number; task_id?: number; description?: string; start_time: string; duration: number; billable: number }>>([])
const trackedApps = ref<Array<{ id: number; exe_name: string; exe_path?: string; display_name?: string; icon?: string }>>([])

interface TaskActual {
  task_id: number
  task_name: string
  estimated_hours: number | null
  hourly_rate: number | null
  actual_hours: number
  variance: number | null
  progress: number | null
}

interface BudgetStatus {
  hours_used: number
  amount_used: number
  budget_hours: number | null
  budget_amount: number | null
  percent_hours: number | null
  percent_amount: number | null
  daily_average_hours: number
  estimated_completion_days: number | null
  hours_remaining: number | null
  pace: string | null
}

const taskActualsData = ref<TaskActual[]>([])
const budgetData = ref<BudgetStatus | null>(null)

const clientName = computed(() => {
  if (!project.value?.client_id) return 'No client'
  const client = clientsStore.clients.find(c => c.id === project.value!.client_id)
  return client?.name || 'Unknown client'
})

const totalHours = computed(() => {
  return projectEntries.value.reduce((sum, e) => sum + e.duration, 0) / 3600
})

const totalRevenue = computed(() => {
  if (!project.value) return 0
  if (project.value.budget_amount) return project.value.budget_amount
  return totalHours.value * project.value.hourly_rate
})

const budgetPct = computed(() => {
  if (!project.value?.budget_hours || !budgetData.value) return 0
  return (budgetData.value.hours_used / project.value.budget_hours) * 100
})

const taskMap = ref<Map<number, string>>(new Map())

function getTaskName(taskId?: number): string {
  if (!taskId) return ''
  return taskMap.value.get(taskId) || ''
}

function formatDuration(seconds: number): string {
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  if (hours > 0) return `${hours}h ${minutes}m`
  return `${minutes}m`
}

onMounted(async () => {
  const projectId = Number(route.params.id)
  if (!projectId || isNaN(projectId)) return

  await Promise.all([
    projectsStore.fetchProjects(),
    clientsStore.fetchClients(),
  ])

  project.value = projectsStore.projects.find(p => p.id === projectId) || null
  if (!project.value) return

  // Load tasks
  tasks.value = await projectsStore.fetchTasks(projectId)
  const map = new Map<number, string>()
  for (const t of tasks.value) {
    if (t.id) map.set(t.id, t.name)
  }
  taskMap.value = map

  // Load entries for this project
  try {
    const allEntries = await invoke<any[]>('get_time_entries', {})
    projectEntries.value = allEntries
      .filter((e: any) => e.project_id === projectId)
      .sort((a: any, b: any) => new Date(b.start_time).getTime() - new Date(a.start_time).getTime())
  } catch {
    projectEntries.value = []
  }

  // Load task actuals
  try {
    taskActualsData.value = await invoke<TaskActual[]>('get_task_actuals', { projectId })
  } catch {
    taskActualsData.value = []
  }

  // Load budget status
  if (project.value.budget_hours) {
    try {
      const today = new Date().toISOString().split('T')[0]
      budgetData.value = await invoke<BudgetStatus>('get_project_budget_status', { projectId, today })
    } catch {
      budgetData.value = null
    }
  }

  // Load tracked apps
  try {
    trackedApps.value = await invoke<any[]>('get_tracked_apps', { projectId })
  } catch {
    trackedApps.value = []
  }
})
</script>
