<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.dashboard.breadcrumb_parent") }}</a>
                </li>
                <li class="breadcrumb-item active" aria-current="page">
                  <span>{{ $t("lavanderia.dashboard.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="d-flex justify-content-between align-items-center mb-3">
            <h4 class="mb-0">{{ $t("lavanderia.dashboard.heading") }}</h4>
            <button
              class="btn btn-outline-primary btn-sm"
              @click="refrescar"
              :disabled="isRefreshing"
            >
              {{ isRefreshing ? "Actualizando..." : "Refrescar" }}
            </button>
          </div>

          <div class="row g-3">
            <div
              v-for="orden in ordenes"
              :key="orden.id"
              class="col-xl-3 col-lg-4 col-md-6 col-sm-12"
            >
              <div
                class="card h-100 orden-card"
                :class="[
                  `orden-${orden.color}`,
                  { 'orden-prioritaria': orden.is_priority }
                ]"
              >
                <div class="card-body d-flex flex-column">
                  <div class="d-flex justify-content-between align-items-center mb-1">
                    <span class="badge bg-light text-dark">
                      {{ orden.folio_unico }}
                    </span>
                    <span
                      class="badge"
                      :class="{
                        'bg-success': orden.color === 'verde',
                        'bg-warning text-dark': orden.color === 'amarillo',
                        'bg-danger': orden.color === 'rojo'
                      }"
                    >
                      {{ orden.color.toUpperCase() }}
                    </span>
                  </div>

                  <h6 class="mb-1 text-truncate" :title="orden.cliente_nombre">
                    {{ orden.cliente_nombre }}
                    <span
                      v-if="orden.is_priority"
                      class="badge bg-danger ms-1"
                    >
                      PRIORIDAD
                    </span>
                  </h6>
                  <p class="mb-1 text-muted small text-truncate">
                    {{ orden.tipo_servicio }}
                  </p>

                  <p class="mb-1 small text-muted etapa-label">
                    Etapa:
                    <strong>{{ etiquetaEtapa(orden.current_step) }}</strong>
                  </p>

                  <p class="mb-1 small text-muted">
                    Tiempo en etapa:
                    <strong>{{ orden.minutos_en_etapa }} min</strong>
                  </p>
                  <p class="mb-2 small text-muted">
                    Entrega:
                    <strong>{{ formatFechaEntregaDisplay(orden.fecha_entrega) }}</strong>
                  </p>
                  <p class="mb-2 small text-muted">
                    Para entrega:
                    <strong>{{ formatHorasParaEntrega(orden.horas_para_entrega) }}</strong>
                  </p>

                  <p
                    v-if="orden.instrucciones"
                    class="mb-2 small instrucciones text-truncate"
                    :title="orden.instrucciones"
                  >
                    {{ orden.instrucciones }}
                  </p>

                  <div class="mt-auto d-flex flex-wrap gap-1">
                    <button
                      type="button"
                      class="btn btn-outline-secondary btn-sm flex-fill"
                      @click="verDetalleOrden(orden)"
                    >
                      Detalles
                    </button>
                    <button
                      type="button"
                      class="btn btn-outline-dark btn-sm flex-fill"
                      :disabled="imprimiendoEtiquetaId === orden.id"
                      @click="imprimirEtiquetaOrden(orden.id)"
                    >
                      {{ imprimiendoEtiquetaId === orden.id ? "Imprimiendo…" : "Imprimir etiqueta" }}
                    </button>
                    <button
                      v-if="puedeEntregar(orden)"
                      type="button"
                      class="btn btn-success btn-sm flex-fill"
                      :disabled="entregandoId === orden.id"
                      @click="entregar(orden)"
                    >
                      {{ entregandoId === orden.id ? "Entregando…" : "Entregar" }}
                    </button>
                  </div>
                </div>
              </div>
            </div>

            <div v-if="!ordenes.length && !isLoading" class="col-12">
              <div class="alert alert-info mb-0 text-center">
                No hay órdenes pendientes o en proceso.
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <OrdenLavanderiaDetalleModal
      v-model="mostrarModalDetalle"
      :order-id="modalOrdenId"
      solo-editar-bolsas
      @saved="onDetalleModalGuardado"
    />

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

<script setup>
import { onMounted, onUnmounted, ref } from "vue";
import { useI18n } from "vue-i18n";
import Loading from "vue-loading-overlay";
import "vue-loading-overlay/dist/css/index.css";
import { useMeta } from "@/composables/use-meta";
import { useOrderStepLabel } from "@/composables/use-order-step-label";
import { usePermissions } from "@/composables/use-permissions";
import OrdenLavanderiaDetalleModal from "@/components/OrdenLavanderiaDetalleModal.vue";
import * as OrdenLavanderiaRepository from "@/repositories/OrdenLavanderiaRepository";
import { useEtiquetaBolsaImpresion } from "@/composables/useEtiquetaBolsaImpresion";
import { formatFechaEntregaDisplay, formatHorasParaEntrega } from "@/utils/fechaEntrega";

const { t } = useI18n();
const { etiquetaEtapa } = useOrderStepLabel();
useMeta({ title: t("lavanderia.dashboard.page_title") });

const { loadPermissions } = usePermissions();

const ordenes = ref([]);
/** Overlay solo en la primera carga (sin datos previos). */
const isLoading = ref(false);
/** Recarga en segundo plano (intervalo, guardar bolsas, etc.). */
const isRefreshing = ref(false);
const entregandoId = ref(null);

const mostrarModalDetalle = ref(false);
const modalOrdenId = ref(null);

const { imprimiendoEtiquetaId, imprimirEtiquetaTermica } = useEtiquetaBolsaImpresion();

const puedeEntregar = (orden) => {
  return orden.current_step === "terminado";
};

const showMessage = (msg = "", type = "success") => {
  const toast = window.Swal.mixin({
    toast: true,
    position: "top-end",
    showConfirmButton: false,
    timer: 3000,
    timerProgressBar: true,
  });

  toast.fire({
    icon: type,
    title: msg,
  });
};

const cargarDatos = async ({ background = false } = {}) => {
  if (background) {
    if (isRefreshing.value) return;
    isRefreshing.value = true;
  } else {
    isLoading.value = true;
  }

  try {
    const response = await OrdenLavanderiaRepository.getDashboardResumen();
    ordenes.value = response.data || [];
  } catch (error) {
    console.error(error);
    if (!background) {
      showMessage("Error al cargar órdenes", "error");
    }
  } finally {
    if (background) {
      isRefreshing.value = false;
    } else {
      isLoading.value = false;
    }
  }
};

const refrescar = () => cargarDatos({ background: true });

const entregar = async (orden) => {
  entregandoId.value = orden.id;
  try {
    await OrdenLavanderiaRepository.marcarEntregada(orden.id);
    showMessage("Orden marcada como entregada", "success");
    await cargarDatos({ background: true });
  } catch (error) {
    console.error(error);
    showMessage("Error al marcar como entregada", "error");
  } finally {
    entregandoId.value = null;
  }
};

const verDetalleOrden = (orden) => {
  modalOrdenId.value = orden.id;
  mostrarModalDetalle.value = true;
};

async function imprimirEtiquetaOrden(ordenId) {
  try {
    const res = await imprimirEtiquetaTermica(ordenId);
    showMessage(res?.message || "Etiqueta enviada a la impresora.", "success");
  } catch (error) {
    showMessage(error?.message || "No se pudo imprimir la etiqueta.", "warning");
  }
}

const onDetalleModalGuardado = () => {
  cargarDatos({ background: true });
};

let intervalId = null;

onMounted(async () => {
  await loadPermissions();
  await cargarDatos();
  intervalId = setInterval(() => {
    if (mostrarModalDetalle.value) return;
    cargarDatos({ background: true });
  }, 15000);
});

onUnmounted(() => {
  if (intervalId) clearInterval(intervalId);
});
</script>

<style scoped>
.orden-card {
  border-width: 3px;
  border-style: solid;
  border-radius: 12px;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  background: #ffffff;
}

.orden-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.12);
}

.orden-verde {
  border-color: #10b981;
  background: linear-gradient(135deg, #ffffff 0%, #f0fdf4 100%);
}

.orden-verde:hover {
  box-shadow: 0 8px 16px rgba(16, 185, 129, 0.2);
}

.orden-amarillo {
  border-color: #f59e0b;
  background: linear-gradient(135deg, #ffffff 0%, #fffbeb 100%);
}

.orden-amarillo:hover {
  box-shadow: 0 8px 16px rgba(245, 158, 11, 0.2);
}

.orden-rojo {
  border-color: #ef4444;
  background: linear-gradient(135deg, #ffffff 0%, #fef2f2 100%);
}

.orden-rojo:hover {
  box-shadow: 0 8px 16px rgba(239, 68, 68, 0.2);
}

.orden-prioritaria {
  box-shadow: 0 0 0 3px rgba(239, 68, 68, 0.25), 0 4px 8px rgba(0, 0, 0, 0.1);
  animation: pulse-priority 2s infinite;
}

@keyframes pulse-priority {
  0%, 100% {
    box-shadow: 0 0 0 3px rgba(239, 68, 68, 0.25), 0 4px 8px rgba(0, 0, 0, 0.1);
  }
  50% {
    box-shadow: 0 0 0 4px rgba(239, 68, 68, 0.35), 0 6px 12px rgba(0, 0, 0, 0.15);
  }
}

.etapa-label {
  font-size: 0.85rem;
  font-weight: 500;
}

.instrucciones {
  font-style: italic;
  color: #6b7280;
  background: #f9fafb;
  padding: 0.5rem;
  border-radius: 6px;
  border-left: 3px solid #06b6d4;
}

.panel {
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06);
}

.btn-outline-primary {
  border-color: #ff7029;
  color: #ff7029;
}

.btn-outline-primary:hover {
  background: linear-gradient(135deg, #ff7029 0%, #e85a10 100%);
  border-color: #e85a10;
  color: #ffffff;
}

.btn-primary {
  background: linear-gradient(135deg, #ff7029 0%, #e85a10 100%);
  border-color: #e85a10;
}

.btn-primary:hover {
  background: linear-gradient(135deg, #ff8f52 0%, #ff7029 100%);
  border-color: #ff7029;
}

.btn-success {
  background: linear-gradient(135deg, #10b981 0%, #059669 100%);
  border-color: #059669;
}

.btn-success:hover {
  background: linear-gradient(135deg, #34d399 0%, #10b981 100%);
  border-color: #10b981;
}
</style>

