<template>
  <AppLayout :title="`Ticket #${ticket.id}`">
    <div class="p-6 max-w-3xl">
      <div class="flex items-center gap-3 mb-6">
        <Link :href="route('ticketing.index')" class="text-sm text-gray-500 hover:underline">← Tickets</Link>
        <h1 class="text-2xl font-bold text-gray-900">Ticket #{{ ticket.id }}</h1>
        <span class="px-2 py-1 rounded text-xs font-medium" :class="statusClass(ticket.status)">
          {{ formatStatus(ticket.status) }}
        </span>
        <span class="px-2 py-1 rounded text-xs font-medium" :class="priorityClass(ticket.priority)">
          {{ ticket.priority }}
        </span>
      </div>

      <!-- Ticket Details -->
      <div class="bg-white rounded-xl shadow p-6 mb-6">
        <div class="flex items-start justify-between mb-4">
          <h2 class="text-lg font-semibold text-gray-900">{{ ticket.title }}</h2>
          <Link :href="route('ticketing.edit', ticket.id)" class="text-sm text-indigo-600 hover:underline">Edit</Link>
        </div>

        <p class="text-sm text-gray-700 whitespace-pre-wrap mb-5">{{ ticket.description }}</p>

        <div class="grid grid-cols-2 gap-4 text-sm text-gray-600 border-t pt-4">
          <div><span class="font-medium">Category:</span> {{ ticket.category }}</div>
          <div><span class="font-medium">Priority:</span> {{ ticket.priority }}</div>
          <div><span class="font-medium">Submitted by:</span> {{ ticket.submitter?.name ?? '—' }}</div>
          <div><span class="font-medium">Assigned to:</span> {{ ticket.assignee?.name ?? 'Unassigned' }}</div>
          <div><span class="font-medium">Created:</span> {{ formatDate(ticket.created_at) }}</div>
          <div><span class="font-medium">Updated:</span> {{ formatDate(ticket.updated_at) }}</div>
        </div>
      </div>

      <!-- Comments -->
      <div class="bg-white rounded-xl shadow p-6 mb-6">
        <h3 class="text-base font-semibold text-gray-800 mb-4">
          Comments ({{ visibleComments.length }})
        </h3>

        <div v-if="visibleComments.length === 0" class="text-sm text-gray-400 py-4 text-center">
          No comments yet.
        </div>

        <div class="space-y-4">
          <div
            v-for="comment in visibleComments"
            :key="comment.id"
            :class="['rounded-lg p-4 text-sm', comment.is_internal ? 'bg-yellow-50 border border-yellow-200' : 'bg-gray-50']"
          >
            <div class="flex items-center justify-between mb-2">
              <span class="font-medium text-gray-800">{{ comment.author?.name ?? 'Unknown' }}</span>
              <span class="text-xs text-gray-400">{{ formatDate(comment.created_at) }}</span>
            </div>
            <p class="text-gray-700 whitespace-pre-wrap">{{ comment.body }}</p>
            <span v-if="comment.is_internal" class="mt-1 inline-block text-xs text-yellow-700 font-medium">Staff note</span>
          </div>
        </div>
      </div>

      <!-- Add Comment Form -->
      <div class="bg-white rounded-xl shadow p-6">
        <h3 class="text-base font-semibold text-gray-800 mb-4">Add Comment</h3>
        <form @submit.prevent="submitComment" class="space-y-4">
          <textarea
            v-model="commentForm.body"
            rows="4"
            placeholder="Write your comment…"
            class="w-full px-4 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-indigo-400"
            :class="{ 'border-red-400': commentErrors.body }"
          />
          <p v-if="commentErrors.body" class="text-xs text-red-500">{{ commentErrors.body }}</p>

          <div v-if="isAdmin" class="flex items-center gap-2">
            <input id="is_internal" v-model="commentForm.is_internal" type="checkbox" class="rounded border-gray-300" />
            <label for="is_internal" class="text-sm text-gray-700">Mark as internal staff note</label>
          </div>

          <div class="flex justify-end">
            <button
              type="submit"
              :disabled="commentProcessing"
              class="px-5 py-2 text-sm text-white rounded-lg transition disabled:opacity-50"
              style="background-color: var(--color-sidebar-active-bg)"
            >
              {{ commentProcessing ? 'Posting…' : 'Post Comment' }}
            </button>
          </div>
        </form>
      </div>
    </div>
  </AppLayout>
</template>

<script setup>
import { ref, computed } from 'vue'
import { Link, useForm } from '@inertiajs/vue3'
import AppLayout from '@/Layouts/AppLayout.vue'

const props = defineProps({
  ticket:  Object,
  isAdmin: { type: Boolean, default: false },
})

const commentForm = useForm({
  body:        '',
  is_internal: false,
})

const commentProcessing = ref(false)
const commentErrors = ref({})

// Non-admins don't see internal notes
const visibleComments = computed(() =>
  props.isAdmin
    ? props.ticket.comments
    : props.ticket.comments.filter(c => !c.is_internal)
)

function submitComment() {
  commentProcessing.value = true
  commentForm.post(route('ticketing.comments.store', props.ticket.id), {
    onError:  (e) => { commentErrors.value = e },
    onSuccess: () => { commentForm.reset() },
    onFinish: () => { commentProcessing.value = false },
  })
}

function formatDate(d) {
  return new Date(d).toLocaleDateString('en-CA')
}

function formatStatus(s) {
  const map = { open: 'Open', in_progress: 'In Progress', resolved: 'Resolved', closed: 'Closed' }
  return map[s] ?? s
}

function statusClass(s) {
  const map = {
    open:        'bg-blue-100 text-blue-700',
    in_progress: 'bg-yellow-100 text-yellow-700',
    resolved:    'bg-green-100 text-green-700',
    closed:      'bg-gray-100 text-gray-600',
  }
  return map[s] ?? 'bg-gray-100 text-gray-600'
}

function priorityClass(p) {
  const map = {
    low:    'bg-gray-100 text-gray-600',
    medium: 'bg-blue-100 text-blue-700',
    high:   'bg-orange-100 text-orange-700',
    urgent: 'bg-red-100 text-red-700',
  }
  return map[p] ?? 'bg-gray-100 text-gray-600'
}
</script>
