<script lang="ts" setup>
import { useForm, Link, router } from '@inertiajs/vue3'
import { ref, computed } from 'vue'
import AdminLayout from '@/Layouts/AdminLayout.vue'
import { resolveTicketStatusColor, resolveTicketPriorityColor } from '@/utils/resolvers'
import type { SupportTicket, TicketTag, CannedResponseItem, Department } from '@/types'

interface StaffUser {
  id: number
  name: string
  email: string
}

interface Props {
  ticket: SupportTicket
  cannedResponses: CannedResponseItem[]
  tags: TicketTag[]
  staffUsers: StaffUser[]
  departments: Department[]
}

defineOptions({ layout: AdminLayout })

const props = defineProps<Props>()

const replyForm = useForm({
  body: '',
  status: '',
  is_internal: false,
  tags: (props.ticket.tags ?? []).map(t => t.id),
  canned_response_id: null as number | null,
})

const statusForm = useForm({
  status: '',
})

const assignForm = useForm({
  assigned_to: props.ticket.assigned_to as number | null,
})

const mergeForm = useForm({
  target_ticket_id: null as number | null,
})

const tagForm = useForm({
  tags: (props.ticket.tags ?? []).map(t => t.id),
})

const statusOptions = [
  { title: 'No Change', value: '' },
  { title: 'Open', value: 'open' },
  { title: 'In Progress', value: 'in_progress' },
  { title: 'Waiting on Customer', value: 'waiting' },
  { title: 'Closed', value: 'closed' },
]

const quickStatusOptions = [
  { title: 'Open', value: 'open', color: 'info' },
  { title: 'In Progress', value: 'in_progress', color: 'success' },
  { title: 'Waiting', value: 'waiting', color: 'warning' },
  { title: 'Closed', value: 'closed', color: 'secondary' },
]

const staffOptions = [
  { title: 'Unassigned', value: null },
  ...props.staffUsers.map(u => ({ title: `${u.name} (${u.email})`, value: u.id })),
]

const statusDialog = ref<boolean>(false)
const pendingStatus = ref<string>('')
const mergeDialog = ref<boolean>(false)
const selectedCannedResponse = ref<number | null>(null)

const visibleReplies = computed(() => {
  return props.ticket.replies ?? []
})

const cannedResponseOptions = computed(() => {
  return props.cannedResponses.map(cr => ({
    title: cr.title + (cr.category ? ` [${cr.category}]` : ''),
    value: cr.id,
  }))
})

const tagOptions = computed(() => {
  return props.tags.map(t => ({
    title: t.name,
    value: t.id,
  }))
})

function applyCannedResponse(): void {
  if (!selectedCannedResponse.value) return
  const found = props.cannedResponses.find(cr => cr.id === selectedCannedResponse.value)
  if (found) {
    replyForm.body = found.content
    replyForm.canned_response_id = found.id
  }
}

function submitReply(): void {
  replyForm.post(`/tickets/${props.ticket.id}/reply`, {
    preserveScroll: true,
    onSuccess: () => {
      replyForm.reset('body', 'status', 'is_internal', 'canned_response_id')
      selectedCannedResponse.value = null
    },
  })
}

function openStatusDialog(newStatus: string): void {
  pendingStatus.value = newStatus
  statusDialog.value = true
}

function confirmStatusUpdate(): void {
  statusForm.status = pendingStatus.value
  statusForm.put(`/tickets/${props.ticket.id}/status`, {
    preserveScroll: true,
    onSuccess: () => {
      statusDialog.value = false
    },
  })
}

function submitAssignment(): void {
  assignForm.post(`/tickets/${props.ticket.id}/assign`, {
    preserveScroll: true,
  })
}

function submitTags(): void {
  tagForm.post(`/tickets/${props.ticket.id}/tags`, {
    preserveScroll: true,
  })
}

function openMergeDialog(): void {
  mergeForm.target_ticket_id = null
  mergeDialog.value = true
}

function confirmMerge(): void {
  mergeForm.post(`/tickets/${props.ticket.id}/merge`, {
    onSuccess: () => {
      mergeDialog.value = false
    },
  })
}

function formatStatus(status: string): string {
  return status.replace(/_/g, ' ')
}

function formatDateTime(dateStr: string): string {
  const date = new Date(dateStr)
  return date.toLocaleString('en-US', {
    month: 'short',
    day: '2-digit',
    year: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  })
}

function getUserInitial(name: string): string {
  return name.charAt(0).toUpperCase()
}

function slaStatusColor(dueAt: string | null, breached: boolean): string {
  if (breached) return 'error'
  if (!dueAt) return 'default'
  const now = new Date()
  const due = new Date(dueAt)
  const hoursLeft = (due.getTime() - now.getTime()) / (1000 * 60 * 60)
  if (hoursLeft <= 0) return 'error'
  if (hoursLeft <= 2) return 'warning'
  return 'success'
}

function timeUntil(dateStr: string | null): string {
  if (!dateStr) return '-'
  const now = new Date()
  const target = new Date(dateStr)
  const diffMs = target.getTime() - now.getTime()
  if (diffMs <= 0) return 'Overdue'
  const hours = Math.floor(diffMs / (1000 * 60 * 60))
  const mins = Math.floor((diffMs % (1000 * 60 * 60)) / (1000 * 60))
  if (hours > 24) {
    const days = Math.floor(hours / 24)
    return `${days}d ${hours % 24}h`
  }
  return `${hours}h ${mins}m`
}
</script>

<template>
  <div>
    <!-- Header -->
    <div class="d-flex align-center justify-space-between mb-6">
      <div class="d-flex align-center gap-4">
        <Link href="/tickets">
          <VBtn variant="text" icon="tabler-arrow-left" size="small" />
        </Link>
        <div>
          <div class="d-flex align-center gap-2 flex-wrap">
            <span class="text-h4 font-weight-bold">Ticket #{{ ticket.id }}</span>
            <VChip
              v-if="ticket.ticket_reference"
              size="small"
              color="secondary"
              variant="tonal"
            >
              {{ ticket.ticket_reference }}
            </VChip>
            <VChip
              :color="resolveTicketStatusColor(ticket.status)"
              size="small"
              class="text-capitalize"
            >
              {{ formatStatus(ticket.status) }}
            </VChip>
            <VChip
              :color="resolveTicketPriorityColor(ticket.priority)"
              size="small"
              class="text-capitalize"
            >
              {{ ticket.priority }}
            </VChip>
            <VChip
              v-if="ticket.merged_into_ticket_id"
              size="small"
              color="warning"
              variant="tonal"
            >
              Merged into #{{ ticket.merged_into_ticket_id }}
            </VChip>
          </div>
          <div class="text-body-2 text-medium-emphasis mt-1">
            {{ ticket.user?.name ?? 'Unknown Customer' }} &middot; {{ ticket.user?.email ?? '' }}
          </div>
        </div>
      </div>
      <VBtn
        color="warning"
        variant="tonal"
        size="small"
        @click="openMergeDialog"
      >
        <VIcon icon="tabler-git-merge" start />
        Merge
      </VBtn>
    </div>

    <VRow>
      <!-- Conversation Thread -->
      <VCol cols="12" lg="8">
        <!-- Ticket Subject Card -->
        <VCard class="mb-4">
          <VCardText>
            <div class="text-h6 font-weight-bold mb-2">
              {{ ticket.subject }}
            </div>
            <div class="d-flex align-center ga-4 text-body-2 text-medium-emphasis flex-wrap">
              <span>
                <VIcon icon="tabler-building" size="16" class="me-1" />
                <span class="text-capitalize">{{ ticket.department_relation?.name ?? ticket.department }}</span>
              </span>
              <span>
                <VIcon icon="tabler-calendar" size="16" class="me-1" />
                {{ formatDateTime(ticket.created_at) }}
              </span>
              <template v-if="ticket.tags && ticket.tags.length > 0">
                <VChip
                  v-for="tag in ticket.tags"
                  :key="tag.id"
                  size="x-small"
                  :color="tag.color"
                  variant="tonal"
                >
                  {{ tag.name }}
                </VChip>
              </template>
            </div>
          </VCardText>
        </VCard>

        <!-- Replies -->
        <div class="d-flex flex-column ga-4 mb-6">
          <VCard
            v-for="reply in visibleReplies"
            :key="reply.id"
            :class="[
              reply.is_staff_reply ? 'border-s-4' : '',
              reply.is_internal ? 'border-warning' : (reply.is_staff_reply ? 'border-primary' : ''),
            ]"
            :variant="reply.is_internal ? 'tonal' : (reply.is_staff_reply ? 'tonal' : 'elevated')"
            :color="reply.is_internal ? 'warning' : undefined"
          >
            <VCardText>
              <div class="d-flex align-center ga-3 mb-3">
                <VAvatar
                  :color="reply.is_internal ? 'warning' : (reply.is_staff_reply ? 'primary' : 'secondary')"
                  variant="tonal"
                  size="36"
                >
                  <span class="text-body-2 font-weight-semibold">
                    {{ getUserInitial(reply.user?.name ?? 'U') }}
                  </span>
                </VAvatar>
                <div>
                  <div class="text-body-1 font-weight-medium">
                    {{ reply.user?.name ?? reply.from_email ?? 'Unknown' }}
                    <VChip
                      v-if="reply.is_internal"
                      size="x-small"
                      color="warning"
                      class="ms-2"
                    >
                      Internal Note
                    </VChip>
                    <VChip
                      v-else-if="reply.is_staff_reply"
                      size="x-small"
                      color="primary"
                      class="ms-2"
                    >
                      Staff
                    </VChip>
                    <VChip
                      v-if="reply.via_email"
                      size="x-small"
                      color="info"
                      variant="tonal"
                      class="ms-2"
                    >
                      Via Email
                    </VChip>
                  </div>
                  <div class="text-caption text-medium-emphasis">
                    {{ formatDateTime(reply.created_at) }}
                  </div>
                </div>
              </div>
              <div class="text-body-2" style="white-space: pre-wrap;">{{ reply.body }}</div>
            </VCardText>
          </VCard>
        </div>

        <!-- Reply Form -->
        <VCard>
          <VCardTitle class="d-flex align-center gap-2">
            <VIcon :icon="replyForm.is_internal ? 'tabler-note' : 'tabler-message'" size="22" />
            <span>{{ replyForm.is_internal ? 'Internal Note' : 'Staff Reply' }}</span>
          </VCardTitle>
          <VCardText>
            <VForm @submit.prevent="submitReply">
              <!-- Canned Response Selector -->
              <div class="d-flex align-center ga-3 mb-4">
                <VSelect
                  v-model="selectedCannedResponse"
                  :items="cannedResponseOptions"
                  label="Insert Canned Response"
                  density="compact"
                  clearable
                  hide-details
                  style="max-width: 400px;"
                />
                <VBtn
                  variant="tonal"
                  size="small"
                  :disabled="!selectedCannedResponse"
                  @click="applyCannedResponse"
                >
                  Insert
                </VBtn>
              </div>

              <VTextarea
                v-model="replyForm.body"
                :placeholder="replyForm.is_internal ? 'Write an internal note (not visible to customer)...' : 'Type your reply to the customer...'"
                rows="5"
                :error-messages="replyForm.errors.body"
                counter="5000"
                maxlength="5000"
                class="mb-4"
                :bg-color="replyForm.is_internal ? 'warning-lighten-5' : undefined"
              />

              <div class="d-flex align-center justify-space-between flex-wrap ga-3">
                <div class="d-flex align-center ga-3">
                  <div style="min-width: 200px;">
                    <VSelect
                      v-model="replyForm.status"
                      :items="statusOptions"
                      label="Update Status"
                      density="compact"
                    />
                  </div>
                  <VCheckbox
                    v-model="replyForm.is_internal"
                    label="Internal Note"
                    density="compact"
                    hide-details
                    color="warning"
                  />
                </div>

                <VBtn
                  type="submit"
                  :color="replyForm.is_internal ? 'warning' : 'primary'"
                  :loading="replyForm.processing"
                  :disabled="replyForm.processing || !replyForm.body.trim()"
                >
                  <VIcon :icon="replyForm.is_internal ? 'tabler-note' : 'tabler-send'" start />
                  {{ replyForm.is_internal ? 'Add Note' : 'Send Reply' }}
                </VBtn>
              </div>
            </VForm>
          </VCardText>
        </VCard>
      </VCol>

      <!-- Sidebar -->
      <VCol cols="12" lg="4">
        <!-- Customer Info -->
        <VCard class="mb-4">
          <VCardTitle class="d-flex align-center gap-2">
            <VIcon icon="tabler-user" size="22" />
            <span>Customer</span>
          </VCardTitle>
          <VCardText v-if="ticket.user">
            <div class="d-flex align-center gap-3 mb-4">
              <VAvatar color="primary" variant="tonal" size="40">
                <span class="text-body-1 font-weight-semibold">
                  {{ getUserInitial(ticket.user.name) }}
                </span>
              </VAvatar>
              <div>
                <div class="text-body-1 font-weight-medium">
                  {{ ticket.user.name }}
                </div>
                <div class="text-body-2 text-medium-emphasis">
                  {{ ticket.user.email }}
                </div>
              </div>
            </div>

            <VList density="compact" class="pa-0">
              <VListItem v-if="ticket.user.status">
                <template #prepend>
                  <span class="text-body-2 text-medium-emphasis" style="min-width: 80px;">Status</span>
                </template>
                <VListItemTitle class="text-body-2 text-capitalize">
                  {{ ticket.user.status }}
                </VListItemTitle>
              </VListItem>
              <VListItem v-if="ticket.user.company">
                <template #prepend>
                  <span class="text-body-2 text-medium-emphasis" style="min-width: 80px;">Company</span>
                </template>
                <VListItemTitle class="text-body-2">
                  {{ ticket.user.company }}
                </VListItemTitle>
              </VListItem>
            </VList>

            <div class="mt-3">
              <Link :href="`/customers/${ticket.user.id}`">
                <VBtn variant="tonal" size="small" color="primary" block>
                  View Customer
                </VBtn>
              </Link>
            </div>
          </VCardText>
        </VCard>

        <!-- Assignment -->
        <VCard class="mb-4">
          <VCardTitle class="d-flex align-center gap-2">
            <VIcon icon="tabler-user-check" size="22" />
            <span>Assignment</span>
          </VCardTitle>
          <VCardText>
            <VSelect
              v-model="assignForm.assigned_to"
              :items="staffOptions"
              label="Assign to"
              density="compact"
              hide-details
              class="mb-3"
            />
            <VBtn
              variant="tonal"
              size="small"
              color="primary"
              block
              :loading="assignForm.processing"
              @click="submitAssignment"
            >
              Update Assignment
            </VBtn>
          </VCardText>
        </VCard>

        <!-- Tags -->
        <VCard class="mb-4">
          <VCardTitle class="d-flex align-center gap-2">
            <VIcon icon="tabler-tags" size="22" />
            <span>Tags</span>
          </VCardTitle>
          <VCardText>
            <VSelect
              v-model="tagForm.tags"
              :items="tagOptions"
              label="Tags"
              density="compact"
              multiple
              chips
              closable-chips
              hide-details
              class="mb-3"
            />
            <VBtn
              variant="tonal"
              size="small"
              color="primary"
              block
              :loading="tagForm.processing"
              @click="submitTags"
            >
              Update Tags
            </VBtn>
          </VCardText>
        </VCard>

        <!-- SLA Info -->
        <VCard v-if="ticket.sla_policy" class="mb-4">
          <VCardTitle class="d-flex align-center gap-2">
            <VIcon icon="tabler-clock" size="22" />
            <span>SLA</span>
          </VCardTitle>
          <VCardText>
            <VList density="compact" class="pa-0">
              <VListItem>
                <template #prepend>
                  <span class="text-body-2 text-medium-emphasis" style="min-width: 110px;">Policy</span>
                </template>
                <VListItemTitle class="text-body-2">
                  {{ ticket.sla_policy.name }}
                </VListItemTitle>
              </VListItem>
              <VListItem>
                <template #prepend>
                  <span class="text-body-2 text-medium-emphasis" style="min-width: 110px;">First Response</span>
                </template>
                <VListItemTitle>
                  <VChip
                    v-if="ticket.first_responded_at"
                    size="small"
                    color="success"
                  >
                    Responded
                  </VChip>
                  <VChip
                    v-else
                    size="small"
                    :color="slaStatusColor(ticket.first_response_due_at, ticket.sla_first_response_breached)"
                  >
                    {{ ticket.sla_first_response_breached ? 'BREACHED' : timeUntil(ticket.first_response_due_at) }}
                  </VChip>
                </VListItemTitle>
              </VListItem>
              <VListItem>
                <template #prepend>
                  <span class="text-body-2 text-medium-emphasis" style="min-width: 110px;">Resolution</span>
                </template>
                <VListItemTitle>
                  <VChip
                    v-if="ticket.resolved_at"
                    size="small"
                    color="success"
                  >
                    Resolved
                  </VChip>
                  <VChip
                    v-else
                    size="small"
                    :color="slaStatusColor(ticket.resolution_due_at, ticket.sla_resolution_breached)"
                  >
                    {{ ticket.sla_resolution_breached ? 'BREACHED' : timeUntil(ticket.resolution_due_at) }}
                  </VChip>
                </VListItemTitle>
              </VListItem>
            </VList>
          </VCardText>
        </VCard>

        <!-- Ticket Details -->
        <VCard class="mb-4">
          <VCardTitle class="d-flex align-center gap-2">
            <VIcon icon="tabler-info-circle" size="22" />
            <span>Ticket Details</span>
          </VCardTitle>
          <VCardText>
            <VList density="compact" class="pa-0">
              <VListItem>
                <template #prepend>
                  <span class="text-body-2 text-medium-emphasis" style="min-width: 100px;">Status</span>
                </template>
                <VListItemTitle>
                  <VChip
                    :color="resolveTicketStatusColor(ticket.status)"
                    size="small"
                    class="text-capitalize"
                  >
                    {{ formatStatus(ticket.status) }}
                  </VChip>
                </VListItemTitle>
              </VListItem>
              <VListItem>
                <template #prepend>
                  <span class="text-body-2 text-medium-emphasis" style="min-width: 100px;">Priority</span>
                </template>
                <VListItemTitle>
                  <VChip
                    :color="resolveTicketPriorityColor(ticket.priority)"
                    size="small"
                    class="text-capitalize"
                  >
                    {{ ticket.priority }}
                  </VChip>
                </VListItemTitle>
              </VListItem>
              <VListItem>
                <template #prepend>
                  <span class="text-body-2 text-medium-emphasis" style="min-width: 100px;">Department</span>
                </template>
                <VListItemTitle class="text-body-2 text-capitalize">
                  {{ ticket.department_relation?.name ?? ticket.department }}
                </VListItemTitle>
              </VListItem>
              <VListItem>
                <template #prepend>
                  <span class="text-body-2 text-medium-emphasis" style="min-width: 100px;">Created</span>
                </template>
                <VListItemTitle class="text-body-2">
                  {{ formatDateTime(ticket.created_at) }}
                </VListItemTitle>
              </VListItem>
              <VListItem v-if="ticket.last_reply_at">
                <template #prepend>
                  <span class="text-body-2 text-medium-emphasis" style="min-width: 100px;">Last Reply</span>
                </template>
                <VListItemTitle class="text-body-2">
                  {{ formatDateTime(ticket.last_reply_at) }}
                </VListItemTitle>
              </VListItem>
            </VList>
          </VCardText>
        </VCard>

        <!-- Quick Status Update -->
        <VCard>
          <VCardTitle class="d-flex align-center gap-2">
            <VIcon icon="tabler-toggle-left" size="22" />
            <span>Update Status</span>
          </VCardTitle>
          <VCardText>
            <div class="d-flex flex-column ga-2">
              <VBtn
                v-for="option in quickStatusOptions"
                :key="option.value"
                :color="option.color"
                variant="tonal"
                block
                :disabled="ticket.status === option.value"
                @click="openStatusDialog(option.value)"
              >
                {{ option.title }}
              </VBtn>
            </div>
          </VCardText>
        </VCard>
      </VCol>
    </VRow>

    <!-- Status Confirmation Dialog -->
    <VDialog v-model="statusDialog" max-width="500" persistent>
      <VCard>
        <VCardTitle class="text-h5 pa-5">
          Update Ticket Status
        </VCardTitle>
        <VCardText class="px-5 pb-2">
          Are you sure you want to change the ticket status to <strong class="text-capitalize">{{ formatStatus(pendingStatus) }}</strong>?
        </VCardText>
        <VCardActions class="pa-5">
          <VSpacer />
          <VBtn variant="text" :disabled="statusForm.processing" @click="statusDialog = false">
            Cancel
          </VBtn>
          <VBtn
            color="primary"
            variant="flat"
            :loading="statusForm.processing"
            @click="confirmStatusUpdate"
          >
            Confirm
          </VBtn>
        </VCardActions>
      </VCard>
    </VDialog>

    <!-- Merge Dialog -->
    <VDialog v-model="mergeDialog" max-width="500" persistent>
      <VCard>
        <VCardTitle class="text-h5 pa-5">
          Merge Ticket
        </VCardTitle>
        <VCardText class="px-5 pb-2">
          <p class="mb-4">
            This will move all replies from this ticket into the target ticket and close this ticket.
          </p>
          <VTextField
            v-model.number="mergeForm.target_ticket_id"
            type="number"
            label="Target Ticket ID"
            :error-messages="mergeForm.errors.target_ticket_id"
            hint="Enter the ticket ID to merge into"
            persistent-hint
          />
        </VCardText>
        <VCardActions class="pa-5">
          <VSpacer />
          <VBtn variant="text" :disabled="mergeForm.processing" @click="mergeDialog = false">
            Cancel
          </VBtn>
          <VBtn
            color="warning"
            variant="flat"
            :loading="mergeForm.processing"
            :disabled="!mergeForm.target_ticket_id"
            @click="confirmMerge"
          >
            Merge
          </VBtn>
        </VCardActions>
      </VCard>
    </VDialog>
  </div>
</template>
