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

interface Props {
  ticket: SupportTicket
}

defineOptions({ layout: AdminLayout })

const props = defineProps<Props>()

const replyForm = useForm({
  body: '',
  status: '',
})

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

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 statusDialog = ref<boolean>(false)
const pendingStatus = ref<string>('')

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

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 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()
}
</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">
            <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>
          </div>
          <div class="text-body-2 text-medium-emphasis mt-1">
            {{ ticket.user?.name ?? 'Unknown Customer' }} &middot; {{ ticket.user?.email ?? '' }}
          </div>
        </div>
      </div>
    </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">
              <span>
                <VIcon icon="tabler-building" size="16" class="me-1" />
                <span class="text-capitalize">{{ ticket.department }}</span>
              </span>
              <span>
                <VIcon icon="tabler-calendar" size="16" class="me-1" />
                {{ formatDateTime(ticket.created_at) }}
              </span>
            </div>
          </VCardText>
        </VCard>

        <!-- Replies -->
        <div class="d-flex flex-column ga-4 mb-6">
          <VCard
            v-for="reply in ticket.replies"
            :key="reply.id"
            :class="reply.is_staff_reply ? 'border-s-4 border-primary' : ''"
            :variant="reply.is_staff_reply ? 'tonal' : 'elevated'"
          >
            <VCardText>
              <div class="d-flex align-center ga-3 mb-3">
                <VAvatar
                  :color="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_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="tabler-message" size="22" />
            <span>Staff Reply</span>
          </VCardTitle>
          <VCardText>
            <VForm @submit.prevent="submitReply">
              <VTextarea
                v-model="replyForm.body"
                placeholder="Type your reply to the customer..."
                rows="5"
                :error-messages="replyForm.errors.body"
                counter="5000"
                maxlength="5000"
                class="mb-4"
              />

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

                <VBtn
                  type="submit"
                  color="primary"
                  :loading="replyForm.processing"
                  :disabled="replyForm.processing || !replyForm.body.trim()"
                >
                  <VIcon icon="tabler-send" start />
                  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>

        <!-- 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 }}
                </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>
  </div>
</template>
