<script setup lang="ts">
import { computed, ref } from 'vue'

import TencentAuthCard from '@/components/tencent/TencentAuthCard.vue'
import TencentRedeemPanel from '@/components/tencent/TencentRedeemPanel.vue'
import TencentResultPanel from '@/components/tencent/TencentResultPanel.vue'
import { useAdminManualRedeemPage } from '@/composables/useAdminManualRedeemPage'
import AdminManualRedeemCreateCard from './components/AdminManualRedeemCreateCard.vue'
import AdminManualRedeemSummaryCard from './components/AdminManualRedeemSummaryCard.vue'
import AdminManualRedeemReviewCard from './components/AdminManualRedeemReviewCard.vue'

const {
  form,
  suggestions,
  detail,
  detailLoading,
  createLoading,
  sessionLoading,
  roleConfirmLoading,
  redeemLoading,
  closeLoading,
  loginType,
  loginTypeLabel,
  loginTabs,
  task,
  order,
  orderItem,
  manualRequest,
  hasSession,
  qrImage,
  qrFigureStyle,
  qrPreviewWidth,
  statusLabel,
  session,
  sessionNotice,
  roleFacts,
  resultFacts,
  roleConfirmed,
  roleReady,
  canConfirmRole,
  canRedeem,
  redeemBlockedReason,
  redeemButtonLabel,
  initButtonLabel,
  scanInstruction,
  screenshotEmptyTitle,
  screenshotEmptyMessage,
  screenshotUrl,
  screenshotLoading,
  reviewReady,
  resultReady,
  canCreateTask,
  hasActiveTask,
  createTaskNow,
  createSessionFlow,
  refreshSessionFlow,
  closeSessionFlow,
  switchLoginType,
  confirmRoleNow,
  redeemNow,
  closeTaskNow,
  resetCurrentTask,
  handleQrImageLoad,
  copyQrImage,
  copyScreenshot,
  downloadScreenshot,
} = useAdminManualRedeemPage()

const qrPreviewVisible = ref(false)
const screenshotPreviewVisible = ref(false)

const currentLoginTabLabel = computed(
  () => loginTabs.find((tab) => tab.value === loginType.value)?.label ?? loginTabs[0].label,
)

const reviewCardTitle = computed(() =>
  task.value?.status === 'redeemed' ? '兑换截图' : '角色复核图',
)
const canStartNextTask = computed(() =>
  Boolean(task.value && ['redeemed', 'closed'].includes(task.value.status)),
)
const taskDetailLink = computed(() =>
  task.value?.taskId ? `/admin/tasks/${task.value.taskId}` : '',
)
</script>

<template>
  <section class="admin-panel manual-redeem-panel">
    <AdminPageHeader
      title="人工兑换"
      description="客服在后台创建唯一任务、发送二维码、复核角色并完成兑换。"
    >
      <template v-if="taskDetailLink">
        <RouterLink :to="taskDetailLink" class="task-link">查看任务详情</RouterLink>
      </template>
      <el-button
        v-if="hasActiveTask"
        :loading="closeLoading"
        plain
        type="danger"
        @click="closeTaskNow"
      >
        关闭当前任务
      </el-button>
      <el-button v-if="canStartNextTask" plain type="primary" @click="resetCurrentTask">
        开始下一单
      </el-button>
    </AdminPageHeader>

    <AdminManualRedeemCreateCard
      :form="form"
      :suggestions="suggestions"
      :can-create-task="canCreateTask"
      :create-loading="createLoading"
      :create-task-now="createTaskNow"
    />

    <AdminManualRedeemSummaryCard
      :task="task"
      :order="order"
      :order-item="orderItem"
      :manual-request="manualRequest"
      :status-label="statusLabel"
    />

    <div v-if="detailLoading && !detail" class="empty-block">人工兑换详情加载中</div>

    <div v-else-if="detail" class="layout-grid">
      <TencentAuthCard
        :current-login-tab-label="currentLoginTabLabel"
        :has-session="hasSession"
        :init-button-label="initButtonLabel"
        :login-tabs="loginTabs"
        :login-type="loginType"
        :login-type-label="loginTypeLabel"
        qr-copy-button-label="复制当前二维码"
        :qr-copy-enabled="true"
        :qr-figure-style="qrFigureStyle"
        :qr-image="qrImage"
        :scan-instruction="scanInstruction"
        :session-status="session?.status || ''"
        :session-id="session?.sessionId || ''"
        :session-loading="sessionLoading"
        :session-notice="sessionNotice"
        @create-session="createSessionFlow"
        @close-session="closeSessionFlow"
        @copy-qr="copyQrImage"
        @open-qr-preview="qrPreviewVisible = true"
        @qr-image-load="handleQrImageLoad"
        @reload-session="refreshSessionFlow"
        @switch-login-type="switchLoginType"
      />

      <div class="control-column">
        <TencentRedeemPanel
          :can-redeem="canRedeem"
          :can-confirm-role="canConfirmRole"
          confirm-action-label="确认当前角色"
          :confirm-action-loading="roleConfirmLoading"
          :confirm-action-visible="!roleConfirmed"
          :confirm-readonly="false"
          :hide-redeem-form="true"
          :login-type-label="loginTypeLabel"
          :max-attempts="6"
          :redeem-blocked-reason="redeemBlockedReason"
          :redeem-button-label="redeemButtonLabel"
          :redeem-code="''"
          :redeem-loading="redeemLoading"
          :role-confirmed="roleConfirmed"
          :role-facts="roleFacts"
          :role-ready="roleReady"
          :status-label="statusLabel"
          @confirm-role="confirmRoleNow"
          @redeem="redeemNow"
          @update:max-attempts="() => undefined"
          @update:redeem-code="() => undefined"
          @update:role-confirmed="() => undefined"
        />
      </div>
    </div>

    <AdminManualRedeemReviewCard
      v-if="detail"
      :review-card-title="reviewCardTitle"
      :review-ready="reviewReady"
      :result-ready="resultReady"
      :screenshot-empty-title="screenshotEmptyTitle"
      :screenshot-empty-message="screenshotEmptyMessage"
      :screenshot-url="screenshotUrl"
      :screenshot-loading="screenshotLoading"
      :copy-screenshot="copyScreenshot"
      :download-screenshot="downloadScreenshot"
      :open-preview="() => (screenshotPreviewVisible = true)"
    />

    <TencentResultPanel
      v-if="detail && task?.status === 'redeemed'"
      :result-facts="resultFacts"
      :screenshot-empty-message="screenshotEmptyMessage"
      :screenshot-empty-title="screenshotEmptyTitle"
      :screenshot-url="screenshotUrl"
      :show-screenshot="Boolean(screenshotUrl)"
      @open-screenshot-preview="screenshotPreviewVisible = true"
    />

    <section v-else-if="!detail && !detailLoading" class="empty-block">
      <strong>还没有进行中的人工兑换任务</strong>
      <p>先在上方输入唯一凭据和内部 SKU，系统会立即校验唯一性并预占库存。</p>
    </section>

    <el-dialog
      v-model="qrPreviewVisible"
      align-center
      class="preview-dialog"
      :width="qrPreviewWidth"
    >
      <div class="qr-preview-body">
        <img
          class="preview-image qr-preview-image"
          :src="qrImage"
          :alt="`Admin Manual Redeem ${loginTypeLabel} QR Preview`"
        />
      </div>
    </el-dialog>

    <el-dialog
      v-model="screenshotPreviewVisible"
      align-center
      class="preview-dialog"
      width="1080px"
    >
      <img class="preview-image" :src="screenshotUrl" alt="Manual redeem screenshot preview" />
    </el-dialog>
  </section>
</template>

<style scoped>
.manual-redeem-panel {
  display: grid;
  gap: 18px;
}

.task-link {
  color: var(--color-primary);
  text-decoration: none;
  font-weight: 600;
}

.layout-grid {
  display: grid;
  grid-template-columns: minmax(340px, 392px) minmax(0, 1fr);
  gap: var(--space-4);
  align-items: stretch;
}

.control-column {
  display: grid;
}

.empty-block {
  min-height: 180px;
  padding: var(--space-6);
  border-radius: var(--radius-xl);
  display: grid;
  place-items: center;
  text-align: center;
  background: var(--bg-surface);
  border: 1px dashed var(--border-default);
  color: var(--text-secondary);
}

.empty-block strong {
  color: var(--text-primary);
  font-size: var(--text-lg);
}

.empty-block p {
  margin: var(--space-2) 0 0;
  line-height: 1.7;
}

.preview-image {
  display: block;
  width: 100%;
  height: auto;
}

@media (max-width: 900px) {
  .summary-card,
  .layout-grid {
    grid-template-columns: 1fr;
  }
}
</style>
