<template>
  <div class="flex h-screen overflow-hidden bg-gray-50 dark:bg-gray-900">
    <!-- Left Rail (240px) -->
    <aside class="w-60 flex-shrink-0 flex flex-col border-r border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 overflow-y-auto">
      <div class="p-4 border-b border-gray-200 dark:border-gray-700">
        <h1 class="text-lg font-semibold text-gray-900 dark:text-white">Ticketing</h1>
      </div>

      <!-- Group Switcher -->
      <div class="p-3 border-b border-gray-200 dark:border-gray-700">
        <label class="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1 uppercase tracking-wide">Group</label>
        <select
          v-model="activeGroupId"
          @change="applyFilter({ group_id: activeGroupId || undefined })"
          class="w-full text-sm border-gray-300 dark:border-gray-600 rounded-md dark:bg-gray-700 dark:text-white"
        >
          <option :value="null">All Groups</option>
          <option v-for="g in groups" :key="g.id" :value="g.id">
            <span :style="{ color: g.color }">●</span> {{ g.name }}
          </option>
        </select>
      </div>

      <!-- Filter Views -->
      <nav class="p-3 space-y-1 border-b border-gray-200 dark:border-gray-700">
        <button
          v-for="view in filterViews"
          :key="view.key"
          @click="applyFilter({ filter: view.key })"
          :class="[
            'w-full text-left px-3 py-1.5 rounded-md text-sm transition-colors',
            activeFilter === view.key
              ? 'bg-indigo-50 text-indigo-700 dark:bg-indigo-900 dark:text-indigo-200 font-medium'
              : 'text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700'
          ]"
        >
          {{ view.label }}
        </button>
      </nav>

      <!-- Priority Filters -->
      <div class="p-3 border-b border-gray-200 dark:border-gray-700">
        <p class="text-xs font-medium text-gray-500 dark:text-gray-400 mb-2 uppercase tracking-wide">Priority</p>
        <div class="flex flex-wrap gap-1">
          <button
            v-for="p in priorities"
            :key="p.id"
            @click="applyFilter({ priority_id: filters.priority_id === p.id ? undefined : p.id })"
            :class="[
              'inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs border transition-colors',
              filters.priority_id === p.id
                ? 'border-current font-semibold'
                : 'border-gray-200 dark:border-gray-600 text-gray-600 dark:text-gray-300'
            ]"
            :style="filters.priority_id === p.id ? { color: p.color, borderColor: p.color } : {}"
          >
            <span :style="{ color: p.color }">●</span> {{ p.name }}
          </button>
        </div>
      </div>

      <!-- Projects -->
      <div class="p-3">
        <p class="text-xs font-medium text-gray-500 dark:text-gray-400 mb-2 uppercase tracking-wide">Projects</p>
        <div class="space-y-1">
          <p v-if="!projects.length" class="text-xs text-gray-400 italic">No active projects</p>
          <button
            v-for="proj in projects"
            :key="proj.id"
            class="w-full text-left px-2 py-1 text-sm text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-md truncate"
          >
            📁 {{ proj.name }}
          </button>
        </div>
      </div>
    </aside>

    <!-- Middle Panel: Ticket Queue -->
    <main class="flex-1 flex flex-col min-w-0 border-r border-gray-200 dark:border-gray-700" style="max-width: 520px;">
      <div class="flex items-center justify-between px-4 py-3 border-b border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800">
        <h2 class="text-sm font-semibold text-gray-700 dark:text-gray-200">
          {{ currentViewLabel }}
          <span class="ml-1.5 text-xs font-normal text-gray-400">({{ tickets.total }})</span>
        </h2>
        <Link
          :href="route('ticketing.create')"
          class="inline-flex items-center gap-1 text-xs bg-indigo-600 text-white px-3 py-1.5 rounded-md hover:bg-indigo-700 transition"
        >
          + New
        </Link>
      </div>

      <div class="overflow-y-auto flex-1">
        <div v-if="tickets.data.length === 0" class="p-8 text-center text-gray-400 dark:text-gray-500 text-sm">
          No tickets found.
        </div>
        <button
          v-for="ticket in tickets.data"
          :key="ticket.id"
          @click="selectTicket(ticket)"
          :class="[
            'w-full text-left px-4 py-3 border-b border-gray-100 dark:border-gray-700 transition-colors hover:bg-gray-50 dark:hover:bg-gray-700',
            selectedTicketId === ticket.id ? 'bg-indigo-50 dark:bg-indigo-900/30 border-l-2 border-l-indigo-500' : ''
          ]"
        >
          <div class="flex items-start justify-between gap-2">
            <div class="min-w-0 flex-1">
              <div class="flex items-center gap-2 mb-0.5">
                <!-- Ticket number badge -->
                <span
                  class="inline-block text-xs font-mono font-semibold px-1.5 py-0.5 rounded text-white"
                  :style="{ backgroundColor: ticket.group?.color || '#6366f1' }"
                >
                  {{ ticket.number }}
                </span>
                <!-- Priority dot -->
                <span
                  v-if="ticket.priority"
                  class="w-2 h-2 rounded-full flex-shrink-0"
                  :style="{ backgroundColor: ticket.priority.color }"
                  :title="ticket.priority.name"
                ></span>
              </div>
              <p class="text-sm font-medium text-gray-800 dark:text-gray-100 truncate">{{ ticket.title }}</p>
              <p class="text-xs text-gray-400 mt-0.5">
                {{ ticket.submitter?.name || ticket.submitter?.email || '—' }}
              </p>
            </div>
            <div class="flex-shrink-0 text-right space-y-1">
              <span :class="statusClass(ticket.status)" class="inline-block text-xs px-2 py-0.5 rounded-full font-medium">
                {{ statusLabel(ticket.status) }}
              </span>
              <p class="text-xs text-gray-400">{{ timeAgo(ticket.created_at) }}</p>
            </div>
          </div>
        </button>
      </div>

      <!-- Pagination -->
      <div v-if="tickets.last_page > 1" class="px-4 py-2 border-t border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 flex justify-between items-center">
        <span class="text-xs text-gray-500">Page {{ tickets.current_page }} of {{ tickets.last_page }}</span>
        <div class="flex gap-2">
          <Link v-if="tickets.prev_page_url" :href="tickets.prev_page_url" class="text-xs text-indigo-600 hover:underline">← Prev</Link>
          <Link v-if="tickets.next_page_url" :href="tickets.next_page_url" class="text-xs text-indigo-600 hover:underline">Next →</Link>
        </div>
      </div>
    </main>

    <!-- Right Panel: Ticket Detail -->
    <div class="flex-1 min-w-0 flex flex-col bg-white dark:bg-gray-800">
      <div v-if="!selectedTicketId" class="flex items-center justify-center h-full text-gray-400 dark:text-gray-500 text-sm">
        Select a ticket to view details
      </div>
      <div v-else class="flex flex-col h-full">
        <!-- We use an iframe-like approach: navigate to show page embedded -->
        <!-- For now, reload the show page in a contained div via Inertia visit -->
        <div class="p-4 text-sm text-gray-500 dark:text-gray-400 flex items-center gap-2 border-b border-gray-200 dark:border-gray-700">
          <span class="font-mono text-xs font-semibold px-1.5 py-0.5 rounded text-white"
            :style="{ backgroundColor: selectedTicket?.group?.color || '#6366f1' }">
            {{ selectedTicket?.number }}
          </span>
          <span class="font-medium text-gray-800 dark:text-gray-100 truncate">{{ selectedTicket?.title }}</span>
          <Link :href="route('ticketing.show', { ticket: selectedTicketId })" class="ml-auto text-xs text-indigo-600 hover:underline">Open →</Link>
        </div>
        <div class="flex-1 flex items-center justify-center text-gray-400 dark:text-gray-500 text-sm">
          <Link
            :href="route('ticketing.show', { ticket: selectedTicketId })"
            class="inline-flex items-center gap-2 text-sm text-indigo-600 hover:underline"
          >
            View full conversation →
          </Link>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { Link, router } from '@inertiajs/vue3'

const props = defineProps({
  tickets: Object,
  groups: Array,
  priorities: Array,
  projects: Array,
  isAgent: Boolean,
  filters: Object,
})

const selectedTicketId = ref(null)
const activeGroupId = ref(props.filters?.group_id || null)
const activeFilter = ref(props.filters?.filter || 'all')

const filterViews = [
  { key: 'all', label: '📥 All Open' },
  { key: 'mine', label: '👤 Mine' },
  { key: 'unassigned', label: '🔲 Unassigned' },
  { key: 'pending', label: '⏳ Pending' },
]

const currentViewLabel = computed(() => {
  return filterViews.find(v => v.key === activeFilter.value)?.label || 'Tickets'
})

const selectedTicket = computed(() => {
  return props.tickets.data.find(t => t.id === selectedTicketId.value) || null
})

function selectTicket(ticket) {
  selectedTicketId.value = ticket.id
}

function applyFilter(newFilters) {
  const merged = { ...props.filters, ...newFilters }
  // Remove undefined/null values
  Object.keys(merged).forEach(k => {
    if (merged[k] === undefined || merged[k] === null) delete merged[k]
  })
  if (newFilters.filter !== undefined) activeFilter.value = newFilters.filter || 'all'
  router.get(route('ticketing.index'), merged, { preserveState: true, replace: true })
}

function statusLabel(status) {
  const map = {
    open: 'Open',
    in_progress: 'In Progress',
    pending: 'Pending',
    resolved: 'Resolved',
    closed: 'Closed',
  }
  return map[status] || status
}

function statusClass(status) {
  const map = {
    open: 'bg-blue-100 text-blue-700 dark:bg-blue-900 dark:text-blue-200',
    in_progress: 'bg-purple-100 text-purple-700 dark:bg-purple-900 dark:text-purple-200',
    pending: 'bg-yellow-100 text-yellow-700 dark:bg-yellow-900 dark:text-yellow-200',
    resolved: 'bg-green-100 text-green-700 dark:bg-green-900 dark:text-green-200',
    closed: 'bg-gray-100 text-gray-500 dark:bg-gray-700 dark:text-gray-400',
  }
  return map[status] || 'bg-gray-100 text-gray-600'
}

function timeAgo(dateStr) {
  const date = new Date(dateStr)
  const now = new Date()
  const diff = Math.floor((now - date) / 1000)
  if (diff < 60) return `${diff}s ago`
  if (diff < 3600) return `${Math.floor(diff / 60)}m ago`
  if (diff < 86400) return `${Math.floor(diff / 3600)}h ago`
  return `${Math.floor(diff / 86400)}d ago`
}
</script>
