<template>
  <section class="opera-panel">
    <header>
      <div>
        <h2>{{ t('task.operaOperations') }}</h2>
        <p v-if="!operations.length">
          {{ t('task.noOperations') }}
        </p>
      </div>

      <label
        v-if="operations.length && showActions"
        class="simulate-toggle"
      >
        <input
          v-model="simulateFailure"
          type="checkbox"
        >
        {{ t('task.simulateFailure') }}
      </label>
    </header>

    <p
      v-if="operationErrorMessage"
      class="operation-error"
    >
      {{ operationErrorMessage }}
    </p>

    <div
      v-if="operations.length"
      class="operation-list"
    >
      <article
        v-for="operation in operations"
        :key="operation.operation_id"
        class="operation-item"
      >
        <div class="operation-item__main">
          <span class="operation-item__sequence">{{ operation.operation_sequence }}</span>
          <div>
            <strong>{{ formatReservationOperaOperation(t, operation.operation_code, operation.operation_name) }}</strong>
            <small class="th-code">{{ operation.operation_code }}</small>
          </div>
        </div>

        <ReservationStatusBadge :status="operation.operation_status" />

        <div
          v-if="showActions"
          class="operation-item__actions"
        >
          <button
            type="button"
            class="icon-button"
            :disabled="!executable || busyOperationId === operation.operation_id"
            :title="t('task.execute')"
            @click="runOperation(operation.operation_id, 'execute')"
          >
            <i
              class="pi pi-play"
              aria-hidden="true"
            />
          </button>
          <button
            type="button"
            class="icon-button"
            :disabled="!executable || busyOperationId === operation.operation_id"
            :title="t('task.retry')"
            @click="runOperation(operation.operation_id, 'retry')"
          >
            <i
              class="pi pi-refresh"
              aria-hidden="true"
            />
          </button>
        </div>

        <p
          v-if="operation.last_error_message"
          class="operation-error"
        >
          {{ operation.last_error_message }}
        </p>
      </article>
    </div>
  </section>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useI18n } from 'vue-i18n'

import ReservationStatusBadge from '@/components/reservation/ReservationStatusBadge.vue'
import { executeReservationOperaOperation, retryReservationOperaOperation } from '@/services/reservationService'
import type { ReservationOperaOperationResult } from '@/types/reservation'
import { formatReservationOperaOperation } from '@/utils/reservationDisplay'

const props = withDefaults(defineProps<{
  taskId: string
  operations: ReservationOperaOperationResult[]
  executable: boolean
  showActions?: boolean
}>(), {
  showActions: true,
})

const emit = defineEmits<{
  operationUpdated: [operation: ReservationOperaOperationResult]
}>()

const { t } = useI18n()
const simulateFailure = ref(false)
const busyOperationId = ref<string | null>(null)
const operationErrorMessage = ref('')

async function runOperation(operationId: string, action: 'execute' | 'retry'): Promise<void> {
  busyOperationId.value = operationId
  operationErrorMessage.value = ''
  try {
    const request = simulateFailure.value
      ? { simulate_success: false, failure_message: 'Frontend simulated OPERA failure' }
      : { simulate_success: true }
    const result =
      action === 'execute'
        ? await executeReservationOperaOperation(props.taskId, operationId, request)
        : await retryReservationOperaOperation(props.taskId, operationId, request)
    emit('operationUpdated', result)
  } catch (error) {
    operationErrorMessage.value = error instanceof Error ? error.message : String(error)
  } finally {
    busyOperationId.value = null
  }
}
</script>

<style scoped>
.opera-panel {
  display: grid;
  gap: 14px;
  border: 1px solid var(--th-color-slate-200);
  border-radius: var(--th-radius-md);
  padding: 16px;
}

.opera-panel header {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 12px;
}

.opera-panel h2,
.opera-panel p {
  margin: 0;
}

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

.opera-panel p,
.simulate-toggle {
  color: var(--th-color-slate-500);
  font-size: 12px;
  line-height: 1.5;
}

.simulate-toggle {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  white-space: nowrap;
}

.operation-list {
  display: grid;
  gap: 10px;
}

.operation-item {
  display: grid;
  grid-template-columns: minmax(0, 1fr) auto auto;
  gap: 10px;
  align-items: center;
  border: 1px solid var(--th-color-slate-200);
  border-radius: var(--th-radius-sm);
  padding: 10px;
}

.operation-item__main {
  display: flex;
  min-width: 0;
  align-items: center;
  gap: 10px;
}

.operation-item__main div {
  display: grid;
  min-width: 0;
  gap: 2px;
}

.operation-item__main strong,
.operation-item__main small {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.operation-item__sequence {
  display: inline-flex;
  width: 28px;
  height: 28px;
  align-items: center;
  justify-content: center;
  border-radius: 999px;
  background: var(--th-color-slate-100);
  color: var(--th-color-slate-700);
  font-size: 12px;
  font-weight: 800;
}

.operation-item__actions {
  display: flex;
  gap: 6px;
}

.icon-button {
  display: inline-flex;
  width: 32px;
  height: 32px;
  align-items: center;
  justify-content: center;
  border: 1px solid var(--th-color-slate-200);
  border-radius: var(--th-radius-sm);
  background: var(--th-color-white);
  color: var(--th-color-blue-600);
  cursor: pointer;
}

.icon-button:disabled {
  cursor: not-allowed;
  opacity: 0.45;
}

.operation-error {
  grid-column: 1 / -1;
  color: var(--th-color-danger);
}

@media (max-width: 720px) {
  .operation-item {
    grid-template-columns: 1fr;
  }
}
</style>
