<template>
  <div class="th-page order-detail-view">
    <div
      v-if="loading"
      class="th-section order-state"
    >
      {{ t('common.loading') }}
    </div>
    <div
      v-else-if="errorMessage"
      class="th-section order-state order-state--error"
    >
      {{ errorMessage }}
    </div>

    <template v-else-if="detail">
      <section class="th-section order-summary">
        <header>
          <div>
            <p>{{ t('order.summary') }}</p>
            <h1>{{ detail.order.display_name }}</h1>
          </div>
          <ReservationStatusBadge :status="detail.order.order_status" />
        </header>

        <dl>
          <div>
            <dt>{{ t('order.groupCode') }}</dt>
            <dd>{{ detail.order.group_code ?? '-' }}</dd>
          </div>
          <div>
            <dt>{{ t('order.confirmationNumber') }}</dt>
            <dd>{{ detail.order.confirmation_number ?? '-' }}</dd>
          </div>
          <div>
            <dt>{{ t('order.temporaryOrderNo') }}</dt>
            <dd>{{ detail.order.temporary_order_no ?? '-' }}</dd>
          </div>
          <div>
            <dt>{{ t('order.blockCode') }}</dt>
            <dd>{{ detail.order.block_code ?? '-' }}</dd>
          </div>
          <div>
            <dt>{{ t('order.createdAt') }}</dt>
            <dd>{{ formatReservationDateTime(detail.order.created_at) }}</dd>
          </div>
          <div>
            <dt>{{ t('order.updatedAt') }}</dt>
            <dd>{{ formatReservationDateTime(detail.order.updated_at) }}</dd>
          </div>
        </dl>
      </section>

      <div class="order-grid">
        <aside class="order-side">
          <section class="th-section side-section">
            <div class="th-section-header">
              <h2 class="th-section-title">
                {{ t('order.taskQueue') }}
              </h2>
            </div>
            <div class="side-section__body">
              <ReservationTaskQueue
                :items="detail.tasks"
                :active-task-id="activeTaskId"
                @open-task="activeTaskId = $event"
              />
            </div>
          </section>

          <section class="th-section source-gap">
            <h2>{{ t('task.evidence') }}</h2>
            <template v-if="activeTask">
              <dl>
                <div>
                  <dt>{{ t('task.sourceSubject') }}</dt>
                  <dd>{{ activeTask.source_subject ?? '-' }}</dd>
                </div>
                <div>
                  <dt>{{ t('task.sourceSender') }}</dt>
                  <dd>{{ activeTask.source_sender_summary ?? '-' }}</dd>
                </div>
                <div>
                  <dt>{{ t('task.sourceReceivedAt') }}</dt>
                  <dd>{{ formatReservationDateTime(activeTask.source_received_at) }}</dd>
                </div>
                <div>
                  <dt>{{ t('order.conversationMessageCount') }}</dt>
                  <dd>{{ activeTask.conversation_message_count ?? '-' }}</dd>
                </div>
              </dl>
              <RouterLink
                v-if="activeTask.source_message_id"
                class="source-link"
                :to="`/reservation/source-messages/${activeTask.source_message_id}/conversation`"
              >
                {{ t('task.viewConversation') }}
              </RouterLink>
              <span
                v-else
                class="source-link source-link--disabled"
              >
                {{ t('common.endpointMissing') }}
              </span>
            </template>
            <p v-else>
              {{ t('common.noData') }}
            </p>
          </section>
        </aside>

        <ReservationTaskDetailPanel
          v-if="activeTaskId"
          :task-id="activeTaskId"
        />
        <section
          v-else
          class="th-section order-state"
        >
          {{ t('common.noData') }}
        </section>
      </div>
    </template>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { RouterLink, useRoute } from 'vue-router'
import { useI18n } from 'vue-i18n'

import ReservationStatusBadge from '@/components/reservation/ReservationStatusBadge.vue'
import ReservationTaskDetailPanel from '@/components/reservation/ReservationTaskDetailPanel.vue'
import ReservationTaskQueue from '@/components/reservation/ReservationTaskQueue.vue'
import { fetchReservationOrderDetail } from '@/services/reservationService'
import { useAuthStore } from '@/stores/authStore'
import type { ReservationOrderDetailResult } from '@/types/reservation'
import { formatReservationDateTime } from '@/utils/reservationFormat'

const route = useRoute()
const { t } = useI18n()
const authStore = useAuthStore()
const loading = ref(false)
const errorMessage = ref('')
const detail = ref<ReservationOrderDetailResult | null>(null)
const activeTaskId = ref('')

const orderId = computed(() => String(route.params.orderId ?? ''))
const activeTask = computed(() => detail.value?.tasks.find((task) => task.task_id === activeTaskId.value) ?? null)

watch(
  orderId,
  (nextOrderId) => {
    void loadOrder(nextOrderId)
  },
  { immediate: true },
)

watch(
  () => authStore.selectedHotelId,
  (nextHotelId, previousHotelId) => {
    if (!nextHotelId || nextHotelId === previousHotelId) {
      return
    }
    void loadOrder(orderId.value)
  },
)

async function loadOrder(nextOrderId: string): Promise<void> {
  loading.value = true
  errorMessage.value = ''
  try {
    const nextOrder = await fetchReservationOrderDetail(nextOrderId)
    detail.value = nextOrder
    activeTaskId.value = nextOrder.tasks[0]?.task_id ?? ''
  } catch (error) {
    detail.value = null
    activeTaskId.value = ''
    errorMessage.value = error instanceof Error ? error.message : String(error)
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.order-detail-view {
  max-width: 1320px;
}

.order-state {
  min-height: 260px;
  display: grid;
  place-items: center;
  color: var(--th-color-slate-500);
  font-weight: 700;
}

.order-state--error {
  color: var(--th-color-danger);
}

.order-summary {
  display: grid;
  gap: 18px;
  padding: 20px;
}

.order-summary header {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 16px;
}

.order-summary p,
.order-summary h1,
.order-summary dl {
  margin: 0;
}

.order-summary p {
  color: var(--th-color-blue-600);
  font-size: 12px;
  font-weight: 800;
}

.order-summary h1 {
  margin-top: 4px;
  color: var(--th-color-slate-900);
  font-size: 26px;
}

.order-summary dl {
  display: grid;
  grid-template-columns: repeat(6, minmax(0, 1fr));
  gap: 16px;
}

.order-summary dt {
  color: var(--th-color-slate-500);
  font-size: 12px;
  font-weight: 700;
}

.order-summary dd {
  margin: 5px 0 0;
  color: var(--th-color-slate-900);
  font-size: 13px;
  font-weight: 800;
  overflow-wrap: anywhere;
}

.order-grid {
  display: grid;
  grid-template-columns: minmax(260px, 340px) minmax(0, 1fr);
  gap: 18px;
  align-items: start;
}

.order-side,
.side-section__body {
  display: grid;
  gap: 14px;
}

.side-section {
  padding-bottom: 16px;
}

.side-section__body {
  padding: 14px 16px 0;
}

.source-gap {
  display: grid;
  gap: 8px;
  padding: 16px;
}

.source-gap h2,
.source-gap p,
.source-gap dl {
  margin: 0;
}

.source-gap h2 {
  color: var(--th-color-slate-900);
  font-size: 15px;
}

.source-gap p {
  color: var(--th-color-slate-500);
  font-size: 13px;
  line-height: 1.6;
}

.source-gap dl {
  display: grid;
  gap: 10px;
}

.source-gap dt {
  color: var(--th-color-slate-500);
  font-size: 12px;
  font-weight: 700;
}

.source-gap dd {
  margin: 4px 0 0;
  color: var(--th-color-slate-900);
  font-size: 13px;
  font-weight: 800;
  overflow-wrap: anywhere;
}

.source-link {
  color: var(--th-color-blue-600);
  font-size: 13px;
  font-weight: 800;
  text-decoration: none;
}

.source-link--disabled {
  color: var(--th-color-slate-500);
}

@media (max-width: 1100px) {
  .order-summary dl {
    grid-template-columns: repeat(3, minmax(0, 1fr));
  }

  .order-grid {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 680px) {
  .order-summary dl {
    grid-template-columns: 1fr;
  }
}
</style>
