<template>
  <div v-uppercase-scope 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("ventas.tickets.breadcrumb_parent") }}</a>
                </li>
                <li class="breadcrumb-item active" aria-current="page">
                  <span>{{ $t("ventas.tickets.breadcrumb_current") }}</span>
                </li>
              </ol>
            </nav>
          </div>
        </li>
      </ul>
    </teleport>

    <div class="row layout-top-spacing">
      <div class="col-12">
        <div class="panel lavanderia-panel p-4">
          <h4 class="mb-2">{{ $t("ventas.tickets.title") }}</h4>
          <p class="text-muted small mb-4">{{ $t("ventas.tickets.subtitle") }}</p>

          <div class="row g-2 mb-3">
            <div class="col-md-3 col-lg-2">
              <label class="form-label small mb-0">{{ $t("ventas.tickets.filter_from") }}</label>
              <input type="date" class="form-control form-control-sm" v-model="filters.created_from" />
            </div>
            <div class="col-md-3 col-lg-2">
              <label class="form-label small mb-0">{{ $t("ventas.tickets.filter_to") }}</label>
              <input type="date" class="form-control form-control-sm" v-model="filters.created_to" />
            </div>
            <div class="col-md-6 col-lg-3">
              <label class="form-label small mb-0">{{ $t("ventas.tickets.filter_client") }}</label>
              <input
                type="text"
                class="form-control form-control-sm"
                v-model="filters.cliente_nombre"
                :placeholder="$t('ventas.tickets.filter_client_ph')"
                @keyup.enter="applyFilters"
              />
            </div>
            <div class="col-md-4 col-lg-2">
              <label class="form-label small mb-0">{{ $t("ventas.tickets.filter_folio") }}</label>
              <input
                type="text"
                class="form-control form-control-sm"
                v-model="filters.folio_unico"
                :placeholder="$t('ventas.tickets.filter_folio_ph')"
                @keyup.enter="applyFilters"
              />
            </div>
            <div class="col-md-4 col-lg-2">
              <label class="form-label small mb-0">{{ $t("ventas.tickets.filter_status") }}</label>
              <select class="form-select form-select-sm" v-model="filters.estatus">
                <option value="">{{ $t("ventas.tickets.filter_status_all") }}</option>
                <option value="pendiente">Pendiente</option>
                <option value="en_proceso">En proceso</option>
                <option value="terminado">Terminado</option>
                <option value="entregado">Entregado</option>
                <option value="cancelado">Cancelado</option>
              </select>
            </div>
            <div class="col-md-4 col-lg-3">
              <label class="form-label small mb-0">{{ $t("ventas.tickets.filter_tipo_servicio") }}</label>
              <select class="form-select form-select-sm" v-model="filters.tipo_servicio_id">
                <option value="">{{ $t("ventas.tickets.filter_priority_all") }}</option>
                <option v-for="pl in tiposServicio" :key="pl.id" :value="pl.id">{{ pl.name }}</option>
              </select>
            </div>
            <div class="col-md-4 col-lg-2">
              <label class="form-label small mb-0">{{ $t("ventas.tickets.filter_flag") }}</label>
              <select class="form-select form-select-sm" v-model="filters.is_priority">
                <option value="">{{ $t("ventas.tickets.filter_flag_all") }}</option>
                <option value="1">{{ $t("ventas.tickets.filter_flag_yes") }}</option>
                <option value="0">{{ $t("ventas.tickets.filter_flag_no") }}</option>
              </select>
            </div>
            <div class="col-md-4 col-lg-2">
              <label class="form-label small mb-0">{{ $t("ventas.tickets.filter_caja") }}</label>
              <input
                type="number"
                min="1"
                step="1"
                class="form-control form-control-sm"
                v-model="filters.caja_id"
                :placeholder="$t('ventas.tickets.filter_caja_ph')"
                @keyup.enter="applyFilters"
              />
            </div>
            <div class="col-md-4 col-lg-1">
              <label class="form-label small mb-0">{{ $t("ventas.tickets.per_page") }}</label>
              <select class="form-select form-select-sm" v-model.number="filters.per_page" @change="applyFilters">
                <option :value="10">10</option>
                <option :value="20">20</option>
                <option :value="50">50</option>
                <option :value="100">100</option>
              </select>
            </div>
            <div class="col-12 d-flex flex-wrap gap-2 align-items-end mt-2">
              <button type="button" class="btn btn-primary btn-sm" :disabled="loading" @click="applyFilters">
                {{ $t("ventas.tickets.search") }}
              </button>
              <button type="button" class="btn btn-outline-secondary btn-sm" :disabled="loading" @click="onReset">
                {{ $t("ventas.tickets.reset") }}
              </button>
              <router-link to="/lavanderia/lista" class="btn btn-outline-primary btn-sm">Lista de órdenes</router-link>
              <button
                v-if="canExportCsv"
                type="button"
                class="btn btn-outline-success btn-sm"
                :disabled="loading || exportingCsv"
                @click="onExportCsv"
              >
                {{ exportingCsv ? $t("ventas.tickets.export_loading") : $t("ventas.tickets.export_csv") }}
              </button>
            </div>
          </div>

          <div v-if="rows.length" class="d-flex flex-wrap align-items-center gap-2 mb-2">
            <span class="small text-muted me-1">{{ $t("ventas.tickets.bulk_hint") }}</span>
            <button type="button" class="btn btn-outline-dark btn-sm" :disabled="loading" @click="selectAllOnPage">
              {{ $t("ventas.tickets.select_page") }}
            </button>
            <button type="button" class="btn btn-outline-dark btn-sm" :disabled="loading" @click="clearSelection">
              {{ $t("ventas.tickets.clear_selection") }}
            </button>
            <button
              type="button"
              class="btn btn-primary btn-sm"
              :disabled="loading || !selectedIds.length || bulkBusy"
              @click="onBulkTicket"
            >
              {{ $t("ventas.tickets.bulk_reprint_ticket") }}
            </button>
          </div>

          <div v-if="error" class="alert alert-danger py-2">{{ error }}</div>

          <div class="table-responsive">
            <table class="table table-sm table-bordered table-hover align-middle">
              <thead class="table-light">
                <tr>
                  <th class="text-center" style="width: 2rem">
                    <span class="visually-hidden">{{ $t("ventas.tickets.table_select") }}</span>
                  </th>
                  <th>{{ $t("ventas.tickets.table_folio") }}</th>
                  <th>{{ $t("ventas.tickets.table_client") }}</th>
                  <th>{{ $t("ventas.tickets.table_date") }}</th>
                  <th>{{ $t("ventas.tickets.table_delivery_date") }}</th>
                  <th>{{ $t("ventas.tickets.table_status") }}</th>
                  <th>{{ $t("ventas.tickets.table_priority") }}</th>
                  <th class="text-center">{{ $t("ventas.tickets.table_caja") }}</th>
                  <th class="text-end">{{ $t("ventas.tickets.table_total") }}</th>
                  <th class="text-center" style="width: 8.2rem">{{ $t("ventas.tickets.table_qr") }}</th>
                  <th class="text-center" style="min-width: 14rem">{{ $t("ventas.tickets.table_actions") }}</th>
                </tr>
              </thead>
              <tbody>
                <tr v-if="loading && rows.length === 0">
                  <td colspan="11" class="text-center text-muted py-4">{{ $t("ventas.tickets.loading") }}</td>
                </tr>
                <tr v-else-if="!loading && rows.length === 0">
                  <td colspan="11" class="text-center text-muted py-4">{{ $t("ventas.tickets.empty") }}</td>
                </tr>
                <tr v-for="row in rows" :key="row.id">
                  <td class="text-center">
                    <input
                      type="checkbox"
                      class="form-check-input"
                      :checked="rowSelected(row.id)"
                      @change="toggleRow(row.id)"
                    />
                  </td>
                  <td class="text-nowrap fw-semibold">{{ row.folio_unico }}</td>
                  <td>{{ row.cliente_nombre }}</td>
                  <td class="text-nowrap small">{{ formatDate(row.created_at) }}</td>
                  <td class="text-nowrap small">{{ formatFechaEntregaDisplay(row.fecha_entrega) }}</td>
                  <td>
                    <span :class="badgeClass(row.estatus)">{{ labelEstatus(row.estatus) }}</span>
                  </td>
                  <td>
                    <span v-if="row.sla_tipo_servicio?.name" class="badge bg-secondary">{{ row.sla_tipo_servicio.name }}</span>
                    <span v-else-if="row.is_priority" class="badge bg-danger">{{ $t("ventas.tickets.priority_badge") }}</span>
                    <span v-else class="text-muted">—</span>
                  </td>
                  <td class="text-center small text-muted">{{ row.caja_id ?? "—" }}</td>
                  <td class="text-end">${{ Number(row.total || 0).toFixed(2) }}</td>
                  <td class="text-center p-1">
                    <SeguimientoBarcodeThumb
                      v-if="row.folio_unico"
                      :folio-unico="row.folio_unico"
                      :codigo-qr="row.codigo_qr"
                      :size="72"
                    />
                  </td>
                  <td class="text-center text-nowrap">
                    <button
                      type="button"
                      class="btn btn-sm btn-outline-secondary me-1"
                      v-if="row.estatus === 'pendiente' && row.current_step === 'recepcion'"
                      @click="onEditOrder(row)"
                    >
                      {{ $t("ventas.tickets.edit_order") }}
                    </button>
                    <button
                      v-if="canSendTicketWhatsApp(row)"
                      type="button"
                      class="btn btn-sm btn-success btn-wa-icon me-1"
                      :disabled="whatsAppTicketBusyId === row.id"
                      :title="$t('ventas.tickets.whatsapp_ticket_hint')"
                      :aria-label="$t('ventas.tickets.whatsapp_ticket_hint')"
                      @click="onWhatsAppTicket(row)"
                    >
                      <span
                        v-if="whatsAppTicketBusyId === row.id"
                        class="spinner-border spinner-border-sm"
                        role="status"
                        :aria-label="$t('ventas.tickets.whatsapp_ticket_loading')"
                      />
                      <WhatsAppIcon v-else :size="18" />
                    </button>
                    <button
                      v-if="canWhatsAppNotify(row)"
                      type="button"
                      class="btn btn-sm btn-outline-success btn-wa-icon me-1"
                      :title="$t('ventas.tickets.whatsapp_ready_hint')"
                      :aria-label="$t('ventas.tickets.whatsapp_ready_hint')"
                      @click="onWhatsAppReady(row)"
                    >
                      <WhatsAppIcon :size="18" />
                    </button>
                    <button
                      v-else-if="row.estatus === 'terminado'"
                      type="button"
                      class="btn btn-sm btn-outline-secondary btn-wa-icon me-1"
                      disabled
                      :title="$t('ventas.tickets.whatsapp_no_phone')"
                      :aria-label="$t('ventas.tickets.whatsapp_no_phone')"
                    >
                      <WhatsAppIcon :size="18" />
                    </button>
                    <button
                      type="button"
                      class="btn btn-sm btn-outline-dark me-1"
                      :disabled="reprintingId === row.id"
                      @click="onReprintLabel(row.id)"
                    >
                      {{ $t("ventas.tickets.reprint_label") }}
                    </button>
                    <button
                      type="button"
                      class="btn btn-sm btn-primary"
                      :disabled="reprintingId === row.id"
                      @click="onReprintTicket(row.id)"
                    >
                      {{ $t("ventas.tickets.reprint_ticket") }}
                    </button>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>

          <div v-if="paginator" class="d-flex flex-wrap justify-content-between align-items-center gap-2 mt-3">
            <p class="small text-muted mb-0">
              {{
                $t("ventas.tickets.page", {
                  n: paginator.current_page,
                  m: paginator.last_page,
                  t: paginator.total,
                })
              }}
            </p>
            <div class="btn-group btn-group-sm">
              <button
                type="button"
                class="btn btn-outline-primary"
                :disabled="loading || paginator.current_page <= 1"
                @click="goToPage(paginator.current_page - 1)"
              >
                {{ $t("ventas.tickets.prev") }}
              </button>
              <button
                type="button"
                class="btn btn-outline-primary"
                :disabled="loading || paginator.current_page >= paginator.last_page"
                @click="goToPage(paginator.current_page + 1)"
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, onMounted, ref } from "vue";
import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
import { usePageTitle } from "@/composables/use-meta";
import { useTickets } from "@/composables/useTickets";
import SeguimientoBarcodeThumb from "@/components/SeguimientoBarcodeThumb.vue";
import WhatsAppIcon from "@/components/WhatsAppIcon.vue";
import { canNotifyOrderReadyWhatsApp, canSendTicketWhatsApp, openOrderReadyWhatsApp, openTicketImageWhatsApp } from "@/utils/whatsapp";
import * as OrdenLavanderiaRepository from "@/repositories/OrdenLavanderiaRepository";
import { formatFechaEntregaDisplay } from "@/utils/fechaEntrega";

const { t, locale } = useI18n();
const router = useRouter();

usePageTitle(computed(() => t("ventas.tickets.page_title")));

const {
  loading,
  error,
  paginator,
  filters,
  rows,
  tiposServicio,
  selectedIds,
  canExportCsv,
  fetchPage,
  applyFilters,
  goToPage,
  resetFilters,
  reprintTicketThermal,
  reprintLabelThermal,
  reprintTicketServerPdf,
  reprintingId,
  toggleRow,
  rowSelected,
  selectAllOnPage,
  clearSelection,
  bulkReprintServer,
  downloadExportCsv,
  initTickets,
} = useTickets();

const exportingCsv = ref(false);
const bulkBusy = ref(false);
const whatsAppTicketBusyId = ref(null);

function formatDate(iso) {
  if (!iso) return "—";
  try {
    return new Date(iso).toLocaleString("es-MX");
  } catch {
    return iso;
  }
}

const estatusLabels = {
  pendiente: "Pendiente",
  en_proceso: "En proceso",
  terminado: "Terminado",
  entregado: "Entregado",
  cancelado: "Cancelado",
};

function labelEstatus(s) {
  return estatusLabels[s] || s || "—";
}

function badgeClass(s) {
  const m = {
    pendiente: "badge bg-warning text-dark",
    en_proceso: "badge bg-info text-dark",
    terminado: "badge bg-primary",
    entregado: "badge bg-success",
    cancelado: "badge bg-danger",
  };
  return m[s] || "badge bg-secondary";
}

async function onReset() {
  await resetFilters();
}

async function onReprintTicket(id) {
  try {
    const res = await reprintTicketThermal(id);
    window.Swal?.fire?.({
      icon: "success",
      title: res?.message || t("ventas.tickets.reprint_ok"),
      toast: true,
      timer: 2800,
      position: "top-end",
      showConfirmButton: false,
    });
  } catch (e) {
    const msg = e?.message || t("ventas.tickets.reprint_error");
    window.Swal?.fire?.({ icon: "warning", title: msg });
  }
}

async function onReprintLabel(id) {
  try {
    const res = await reprintLabelThermal(id);
    window.Swal?.fire?.({
      icon: "success",
      title: res?.message || t("ventas.tickets.reprint_label_ok"),
      toast: true,
      timer: 2800,
      position: "top-end",
      showConfirmButton: false,
    });
  } catch (e) {
    const msg = e?.message || t("ventas.tickets.reprint_label_error");
    window.Swal?.fire?.({ icon: "warning", title: msg });
  }
}

async function onExportCsv() {
  exportingCsv.value = true;
  try {
    await downloadExportCsv();
    window.Swal?.fire?.({ icon: "success", title: t("ventas.tickets.export_ok"), toast: true, timer: 2500, position: "top-end", showConfirmButton: false });
  } catch (e) {
    const msg = e.response?.status === 403 ? t("ventas.tickets.export_forbidden") : t("ventas.tickets.export_error");
    window.Swal?.fire?.({ icon: "error", title: msg });
  } finally {
    exportingCsv.value = false;
  }
}

async function onBulkTicket() {
  bulkBusy.value = true;
  try {
    await bulkReprintServer();
  } catch {
    window.Swal?.fire?.({ icon: "error", title: t("ventas.tickets.pdf_error") });
  } finally {
    bulkBusy.value = false;
  }
}

function onEditOrder(row) {
  if (!row) return;
  const query = row.folio_unico
    ? { edit_folio: row.folio_unico }
    : row.id
      ? { edit_id: String(row.id) }
      : null;
  if (!query) return;
  router.push({ name: "ventas-pos-router", query });
}

function canWhatsAppNotify(row) {
  return canNotifyOrderReadyWhatsApp(row);
}

function onWhatsAppReady(row) {
  const ok = openOrderReadyWhatsApp(row, {
    trackingBaseUrl: window.location.origin,
    locale: locale.value,
  });
  if (!ok) {
    window.Swal?.fire?.({ icon: "warning", title: t("ventas.tickets.whatsapp_no_phone") });
  }
}

async function onWhatsAppTicket(row) {
  if (!row?.id) return;
  whatsAppTicketBusyId.value = row.id;
  try {
    const full = await OrdenLavanderiaRepository.getById(row.id);
    const orden = full?.data ?? row;
    const result = await openTicketImageWhatsApp(orden, { locale: locale.value });
    if (!result.ok) {
      if (result.reason === "cancelled") return;
      window.Swal?.fire?.({ icon: "warning", title: t("ventas.tickets.whatsapp_no_phone") });
      return;
    }
    let title = t("ventas.tickets.whatsapp_ticket_ok_download");
    if (result.method === "share") {
      title = t("ventas.tickets.whatsapp_ticket_ok_share");
    } else if (result.copied) {
      title = t("ventas.tickets.whatsapp_ticket_ok_copied");
    }
    window.Swal?.fire?.({
      icon: "success",
      title,
      toast: true,
      timer: 4500,
      position: "top-end",
      showConfirmButton: false,
    });
  } catch {
    window.Swal?.fire?.({ icon: "error", title: t("ventas.tickets.whatsapp_ticket_error") });
  } finally {
    whatsAppTicketBusyId.value = null;
  }
}

onMounted(() => initTickets());
</script>

<style scoped>
.btn-wa-icon {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 2rem;
  height: 2rem;
  padding: 0;
  line-height: 1;
}
</style>
