<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:;">Lavandería</a>
                </li>
                <li class="breadcrumb-item active" aria-current="page">
                  <span>Dashboard Semáforo</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">Órdenes en tiempo real</h4>
            <button
              class="btn btn-outline-primary btn-sm"
              @click="refrescar"
              :disabled="isLoading"
            >
              {{ isLoading ? "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-2 small text-muted">
                    Tiempo en etapa:
                    <strong>{{ orden.minutos_en_etapa }} min</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 justify-content-between gap-1">
                    <button
                      class="btn btn-outline-secondary btn-sm flex-fill"
                      @click="abrirDetalles(orden)"
                    >
                      Detalles
                    </button>
                    <button
                      v-if="puedeAvanzar(orden)"
                      class="btn btn-primary btn-sm flex-fill"
                      @click="avanzar(orden)"
                    >
                      Avanzar
                    </button>
                    <button
                      v-if="puedeEntregar(orden)"
                      class="btn btn-success btn-sm flex-fill"
                      @click="entregar(orden)"
                    >
                      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>

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

<script setup>
import { onMounted, ref } from "vue";
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";

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

const ordenes = ref([]);
const isLoading = ref(false);

const etiquetaEtapa = (step) => {
  const map = {
    recepcion: "Recepción",
    lavado: "Lavado",
    secado: "Secado",
    planchado: "Planchado",
    terminado: "Terminado",
    entregado: "Entregado",
  };
  return map[step] || step;
};

const puedeAvanzar = (orden) => {
  return !["terminado", "entregado"].includes(orden.current_step);
};

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 () => {
  isLoading.value = true;
  try {
    const response = await OrdenLavanderiaRepository.getDashboardResumen();
    ordenes.value = response.data || [];
  } catch (error) {
    console.error(error);
    showMessage("Error al cargar órdenes", "error");
  } finally {
    isLoading.value = false;
  }
};

const refrescar = async () => {
  await cargarDatos();
};

const avanzar = async (orden) => {
  try {
    isLoading.value = true;
    const response = await OrdenLavanderiaRepository.avanzarOrden(orden.id);
    showMessage("Orden actualizada", "success");
    await cargarDatos();
  } catch (error) {
    console.error(error);
    showMessage("Error al avanzar la orden", "error");
  } finally {
    isLoading.value = false;
  }
};

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

const abrirDetalles = (orden) => {
  const detalles = `
Folio: ${orden.folio_unico}
Cliente: ${orden.cliente_nombre}
Servicio: ${orden.tipo_servicio}
Etapa: ${etiquetaEtapa(orden.current_step)}
Minutos en etapa: ${orden.minutos_en_etapa}
Instrucciones: ${orden.instrucciones || "N/A"}
`;
  showMessage(detalles, "info");
};

onMounted(async () => {
  await cargarDatos();
  // Opcional: auto-refresh cada 30s para panel de monitoreo
  // setInterval(cargarDatos, 30000);
});
</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: #2563eb;
  color: #2563eb;
}

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

.btn-primary {
  background: linear-gradient(135deg, #2563eb 0%, #1e3a8a 100%);
  border-color: #1e3a8a;
}

.btn-primary:hover {
  background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
  border-color: #2563eb;
}

.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>

