<template>
  <div class="layout-px-spacing">
    <teleport to="#breadcrumb">
      <ul class="navbar-nav flex-row">
        <li>
          <div class="page-header">
            <nav class="breadcrumb-one" aria-label="breadcrumb">
              <ol class="breadcrumb">
                <li class="breadcrumb-item">
                  <a href="javascript:;">{{ $t("lavanderia.escanear.breadcrumb_parent") }}</a>
                </li>
                <li class="breadcrumb-item active" aria-current="page">
                  <span>{{ $t("lavanderia.escanear.breadcrumb_current") }}</span>
                </li>
              </ol>
            </nav>
          </div>
        </li>
      </ul>
    </teleport>

    <div class="row layout-top-spacing">
      <div class="col-xl-12 col-lg-12 col-sm-12 layout-spacing">
        <div class="panel p-3">
          <div class="row">
            <div class="col-xl-12 col-lg-12 col-sm-12">
              <div class="text-center titulo-dorado">
                <h3 class="pull-left">{{ $t("lavanderia.escanear.heading") }}</h3>
              </div>
            </div>
          </div>
          <div class="row mt-4">
            <div class="col-md-6 offset-md-3">
              <div class="card">
                <div class="card-body">
                  <div class="form-group mb-3">
                    <label>{{ $t("lavanderia.escanear.scan_label") }}</label>
                    <input
                      type="text"
                      class="form-control form-control-lg text-center"
                      :placeholder="$t('lavanderia.escanear.scan_placeholder')"
                      v-model="codigo"
                      @keyup.enter="escanear"
                      autofocus
                    />
                    <p class="small text-muted mt-2 mb-0">
                      {{ $t("lavanderia.escanear.scan_hint") }}
                    </p>
                  </div>
                  <button
                    type="button"
                    class="btn btn-primary btn-lg w-100"
                    @click="escanear"
                    :disabled="!codigo || escaneando"
                  >
                    {{
                      escaneando
                        ? $t("lavanderia.escanear.scan_btn_loading")
                        : $t("lavanderia.escanear.scan_btn")
                    }}
                  </button>
                </div>
              </div>

              <div v-if="ordenEncontrada" class="card mt-3">
                <div class="card-body">
                  <h5 class="card-title text-success">
                    ✓
                    {{
                      $t("lavanderia.escanear.found_line", {
                        folio: ordenEncontrada.folio_unico,
                      })
                    }}
                  </h5>
                  <p class="mb-1">
                    <strong>{{ $t("lavanderia.escanear.client_label") }}:</strong>
                    {{ ordenEncontrada.cliente_nombre }}
                  </p>
                  <p class="mb-1">
                    <strong>{{ $t("lavanderia.escanear.service_label") }}:</strong>
                    {{ ordenEncontrada.tipo_servicio }}
                  </p>
                  <p class="mb-1">
                    <strong>{{ $t("lavanderia.escanear.stage_label") }}:</strong>
                    <span class="badge bg-info ms-1">
                      {{ etiquetaEtapa(ordenEncontrada.current_step) }}
                    </span>
                  </p>
                  <p v-if="ordenEncontrada.instrucciones" class="mb-2">
                    <strong>{{ $t("lavanderia.escanear.instructions_label") }}:</strong>
                    <span class="text-warning">
                      {{ ordenEncontrada.instrucciones }}
                    </span>
                  </p>
                  <div class="alert alert-info mt-2 mb-0">
                    El avance de etapa ahora se realiza solo con escaneo por área (primer escaneo inicia, segundo escaneo finaliza y mueve al siguiente proceso).
                  </div>
                </div>
              </div>

              <div v-if="errorMensaje" class="alert alert-danger mt-3">
                {{ errorMensaje }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <loading
      v-model:active="isLoading"
      :can-cancel="false"
      :is-full-page="true"
    />
  </div>
</template>

<script setup>
import { ref } from "vue";
import axios from "axios";
import Loading from "vue-loading-overlay";
import "vue-loading-overlay/dist/css/index.css";
import { useMeta } from "@/composables/use-meta";
import * as OrdenLavanderiaRepository from "@/repositories/OrdenLavanderiaRepository";
import { normalizeLaundryScanInput } from "@/utils/laundryScanInput";

useMeta({ title: "Escanear QR Lavandería" });

const codigo = ref("");
const escaneando = ref(false);
const isLoading = ref(false);
const ordenEncontrada = ref(null);
const errorMensaje = ref("");

const showMessage = (msg = "", type = "success") => {
  const toast = window.Swal.mixin({
    toast: true,
    position: "top",
    showConfirmButton: false,
    timer: 3000,
  });
  toast.fire({
    icon: type,
    title: msg,
    padding: "10px 20px",
  });
};

const escanear = async () => {
  if (!codigo.value.trim()) {
    showMessage("Ingrese un código QR o folio", "warning");
    return;
  }

  escaneando.value = true;
  isLoading.value = true;
  errorMensaje.value = "";
  ordenEncontrada.value = null;

  try {
    const raw = normalizeLaundryScanInput(codigo.value);
    codigo.value = raw;
    // Intentar primero como codigo_qr (payload del ticket), luego como folio
    let response;
    try {
      response = await OrdenLavanderiaRepository.escanearQR(raw);
    } catch (e) {
      response = await OrdenLavanderiaRepository.escanearFolio(raw);
    }

    if (response.data && response.encontrada) {
      ordenEncontrada.value = response.data;
      showMessage("Orden encontrada", "success");
    } else {
      errorMensaje.value =
        response.errors?.orden?.[0] || "Orden no encontrada o inválida";
    }
  } catch (error) {
    if (axios.isAxiosError(error)) {
      const errorData = error.response?.data;
      errorMensaje.value =
        errorData?.errors?.orden?.[0] ||
        errorData?.message ||
        "Error al escanear la orden";
    } else {
      errorMensaje.value = "Error inesperado al escanear";
    }
  } finally {
    escaneando.value = false;
    isLoading.value = false;
  }
};

</script>

<style scoped>
.card {
  transition: all 0.3s ease;
}
</style>
