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

    <div class="row layout-top-spacing">
      <div class="col-12">
        <div class="panel lavanderia-panel p-4">
          <div class="d-flex flex-wrap justify-content-between align-items-center mb-3 gap-2">
            <div>
              <h4 class="mb-0">{{ $t("admin.impresoras.title") }}</h4>
              <p class="text-muted small mb-0 mt-1">{{ $t("admin.impresoras.subtitle") }}</p>
            </div>
            <div>
              <button type="button" class="btn btn-outline-secondary me-2" :disabled="loading" @click="cargar">
                {{ $t("admin.impresoras.refresh") }}
              </button>
              <button type="button" class="btn btn-primary" @click="abrirNuevo">{{ $t("admin.impresoras.new") }}</button>
            </div>
          </div>

          <div class="alert alert-info py-2 small mb-3">
            {{ $t("admin.impresoras.pos_hint") }}
            <span v-if="fallbackAreaName">
              {{ $t("admin.impresoras.pos_hint_fallback", { area: fallbackAreaName }) }}
            </span>
          </div>

          <div class="row mb-3">
            <div class="col-md-4">
              <label class="form-label">{{ $t("admin.impresoras.filter_area") }}</label>
              <select v-model="filtroAreaId" class="form-select" @change="cargar">
                <option value="">{{ $t("admin.impresoras.filter_all") }}</option>
                <option v-for="a in areas" :key="a.id" :value="String(a.id)">{{ a.name }}</option>
              </select>
            </div>
          </div>

          <div v-if="loading" class="text-center py-5">
            <div class="spinner-border text-primary" role="status"></div>
          </div>
          <div v-else class="table-responsive">
            <table class="table table-bordered table-hover">
              <thead>
                <tr>
                  <th>{{ $t("admin.impresoras.th_area") }}</th>
                  <th>{{ $t("admin.impresoras.th_codigo") }}</th>
                  <th>{{ $t("admin.impresoras.th_nombre") }}</th>
                  <th>{{ $t("admin.impresoras.th_sistema") }}</th>
                  <th>{{ $t("admin.impresoras.th_tipo") }}</th>
                  <th>{{ $t("admin.impresoras.th_red") }}</th>
                  <th>{{ $t("admin.impresoras.th_activa") }}</th>
                  <th>{{ $t("admin.impresoras.th_default") }}</th>
                  <th>{{ $t("admin.impresoras.th_actions") }}</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="row in rows" :key="row.id">
                  <td>{{ row.area?.name || "—" }}</td>
                  <td><code>{{ row.codigo }}</code></td>
                  <td>{{ row.nombre }}</td>
                  <td class="small">{{ row.nombre_sistema }}</td>
                  <td>{{ tipoLabel(row.tipo_ticket) }}</td>
                  <td class="small">
                    <span v-if="row.ip">{{ row.ip }}:{{ row.puerto }}</span>
                    <span v-else class="text-muted">—</span>
                  </td>
                  <td>
                    <span class="badge" :class="row.activa ? 'bg-success' : 'bg-secondary'">
                      {{ row.activa ? $t("admin.impresoras.yes") : $t("admin.impresoras.no") }}
                    </span>
                  </td>
                  <td>
                    <span v-if="row.es_por_defecto" class="badge bg-info">{{ $t("common.label_predeterminado") }}</span>
                    <span v-else class="text-muted">—</span>
                  </td>
                  <td class="text-nowrap">
                    <button
                      type="button"
                      class="btn btn-sm btn-outline-success me-1"
                      :disabled="testingId === row.id"
                      @click="probarImpresion(row)"
                    >
                      {{ testingId === row.id ? $t("admin.impresoras.test_loading") : $t("admin.impresoras.test_btn") }}
                    </button>
                    <button type="button" class="btn btn-sm btn-outline-primary me-1" @click="abrirEditar(row)">{{ $t("admin.impresoras.edit") }}</button>
                    <button type="button" class="btn btn-sm btn-outline-danger" @click="eliminar(row)">{{ $t("common.delete_btn") }}</button>
                  </td>
                </tr>
                <tr v-if="!rows.length">
                  <td colspan="9" class="text-center text-muted py-4">{{ $t("admin.impresoras.empty") }}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>

    <div class="modal fade" id="modalImpresoraAdmin" tabindex="-1" ref="modalEl">
      <div class="modal-dialog modal-lg">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">{{ editando ? $t("admin.impresoras.modal_edit") : $t("admin.impresoras.modal_new") }}</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            <div class="row">
              <div class="col-md-6 mb-3">
                <label class="form-label">{{ $t("admin.impresoras.f_area") }} *</label>
                <select v-model.number="form.area_id" class="form-select" required>
                  <option :value="null" disabled>{{ $t("admin.impresoras.f_area_placeholder") }}</option>
                  <option v-for="a in areas" :key="a.id" :value="a.id">{{ a.name }}</option>
                </select>
              </div>
              <div v-if="editando" class="col-md-6 mb-3">
                <label class="form-label">{{ $t("admin.impresoras.f_codigo") }}</label>
                <input v-model="form.codigo" class="form-control" disabled />
              </div>
              <div :class="editando ? 'col-md-12 mb-3' : 'col-md-6 mb-3'">
                <label class="form-label">{{ $t("admin.impresoras.f_nombre") }} *</label>
                <input v-model="form.nombre" class="form-control" maxlength="255" required />
              </div>
              <div class="col-md-6 mb-3">
                <label class="form-label">{{ $t("admin.impresoras.f_sistema") }} *</label>
                <input v-model="form.nombre_sistema" class="form-control" maxlength="255" required />
                <div class="form-text">{{ $t("admin.impresoras.f_sistema_hint") }}</div>
              </div>
              <div class="col-md-4 mb-3">
                <label class="form-label">{{ $t("admin.impresoras.f_tipo") }} *</label>
                <select v-model="form.tipo_ticket" class="form-select">
                  <option value="venta">{{ $t("admin.impresoras.tipo_venta") }}</option>
                  <option value="cocina">{{ $t("admin.impresoras.tipo_cocina") }}</option>
                </select>
              </div>
              <div class="col-md-4 mb-3">
                <label class="form-label">{{ $t("admin.impresoras.f_ip") }}</label>
                <input v-model="form.ip" class="form-control" maxlength="45" placeholder="192.168.1.50" />
              </div>
              <div class="col-md-4 mb-3">
                <label class="form-label">{{ $t("admin.impresoras.f_puerto") }}</label>
                <input v-model.number="form.puerto" type="number" min="1" max="65535" class="form-control" />
              </div>
              <div class="col-md-4 mb-3">
                <label class="form-label">{{ $t("admin.impresoras.f_ancho") }}</label>
                <input v-model.number="form.ancho_papel" type="number" min="32" max="120" class="form-control" />
              </div>
              <div class="col-md-4 mb-3">
                <label class="form-label">{{ $t("admin.impresoras.f_activa") }}</label>
                <select v-model="form.activa" class="form-select">
                  <option :value="true">{{ $t("admin.impresoras.yes") }}</option>
                  <option :value="false">{{ $t("admin.impresoras.no") }}</option>
                </select>
              </div>
              <div class="col-md-4 mb-3">
                <label class="form-label">{{ $t("admin.impresoras.f_default") }}</label>
                <select v-model="form.es_por_defecto" class="form-select">
                  <option :value="true">{{ $t("admin.impresoras.yes") }}</option>
                  <option :value="false">{{ $t("admin.impresoras.no") }}</option>
                </select>
                <div class="form-text">{{ $t("admin.impresoras.f_default_hint") }}</div>
              </div>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-light" data-bs-dismiss="modal">{{ $t("admin.impresoras.cancel") }}</button>
            <button type="button" class="btn btn-primary" :disabled="saving" @click="guardar">{{ saving ? $t("admin.impresoras.saving") : $t("admin.impresoras.save") }}</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { useI18n } from "vue-i18n";
import { useConfirmDelete } from "@/composables/useConfirmDelete";
import * as ImpresorasAdminRepository from "@/repositories/ImpresorasAdminRepository";

const { t } = useI18n();
const { confirmDelete } = useConfirmDelete();

const loading = ref(true);
const saving = ref(false);
const testingId = ref(null);
const rows = ref([]);
const areas = ref([]);
const fallbackTicketAreaCode = ref("reception");
const filtroAreaId = ref("");
const editando = ref(false);
const editId = ref(null);
const modalEl = ref(null);
let modalInstance = null;

const form = ref(emptyForm());

function emptyForm() {
  return {
    area_id: null,
    codigo: "",
    nombre: "",
    nombre_sistema: "",
    ip: "",
    puerto: 9100,
    tipo_ticket: "venta",
    activa: true,
    es_por_defecto: false,
    ancho_papel: 80,
  };
}

const fallbackAreaName = computed(() => {
  const area = areas.value.find((a) => a.code === fallbackTicketAreaCode.value);
  return area?.name || "";
});

function toast(msg, icon) {
  const mix = window.Swal?.mixin({ toast: true, position: "top-end", showConfirmButton: false, timer: 3500 });
  mix?.fire({ icon, title: msg });
}

function tipoLabel(tipo) {
  return tipo === "cocina" ? t("admin.impresoras.tipo_cocina") : t("admin.impresoras.tipo_venta");
}

async function cargar() {
  loading.value = true;
  try {
    const params = filtroAreaId.value ? { area_id: filtroAreaId.value } : {};
    const res = await ImpresorasAdminRepository.list(params);
    rows.value = Array.isArray(res?.data) ? res.data : [];
    areas.value = Array.isArray(res?.meta?.areas) ? res.meta.areas : [];
    fallbackTicketAreaCode.value = res?.meta?.fallback_ticket_area_code || "reception";
  } catch {
    rows.value = [];
    toast(t("admin.impresoras.load_error"), "error");
  } finally {
    loading.value = false;
  }
}

function abrirNuevo() {
  editando.value = false;
  editId.value = null;
  form.value = emptyForm();
  if (areas.value.length) {
    form.value.area_id = areas.value[0].id;
  }
  modalInstance?.show();
}

function abrirEditar(row) {
  editando.value = true;
  editId.value = row.id;
  form.value = {
    area_id: row.area_id,
    codigo: row.codigo,
    nombre: row.nombre,
    nombre_sistema: row.nombre_sistema,
    ip: row.ip || "",
    puerto: row.puerto ?? 9100,
    tipo_ticket: row.tipo_ticket || "venta",
    activa: !!row.activa,
    es_por_defecto: !!row.es_por_defecto,
    ancho_papel: row.ancho_papel ?? 80,
  };
  modalInstance?.show();
}

function buildPayload() {
  const payload = {
    area_id: form.value.area_id,
    nombre: form.value.nombre?.trim(),
    nombre_sistema: form.value.nombre_sistema?.trim(),
    ip: form.value.ip?.trim() || null,
    puerto: form.value.puerto || 9100,
    tipo_ticket: form.value.tipo_ticket,
    activa: form.value.activa,
    es_por_defecto: form.value.es_por_defecto,
    ancho_papel: form.value.ancho_papel || 80,
  };
  return payload;
}

async function guardar() {
  if (!form.value.area_id || !form.value.nombre?.trim() || !form.value.nombre_sistema?.trim()) {
    toast(t("admin.impresoras.validation_required"), "warning");
    return;
  }
  saving.value = true;
  try {
    const payload = buildPayload();
    if (editando.value && editId.value) {
      await ImpresorasAdminRepository.update(editId.value, payload);
      toast(t("admin.impresoras.updated"), "success");
    } else {
      await ImpresorasAdminRepository.create(payload);
      toast(t("admin.impresoras.created"), "success");
    }
    modalInstance?.hide();
    await cargar();
  } catch (err) {
    const msg = err?.response?.data?.message || t("admin.impresoras.save_error");
    toast(msg, "error");
  } finally {
    saving.value = false;
  }
}

async function probarImpresion(row) {
  testingId.value = row.id;
  try {
    const res = await ImpresorasAdminRepository.testPrint(row.id);
    toast(res?.message || t("admin.impresoras.test_ok"), "success");
  } catch (err) {
    const msg =
      err?.response?.data?.message ||
      err?.response?.data?.errors?.impresion?.[0] ||
      t("admin.impresoras.test_error");
    toast(msg, "error");
  } finally {
    testingId.value = null;
  }
}

async function eliminar(row) {
  const ok = await confirmDelete(row.nombre);
  if (!ok) return;
  try {
    await ImpresorasAdminRepository.remove(row.id);
    toast(t("admin.impresoras.deleted"), "success");
    await cargar();
  } catch (err) {
    const msg = err?.response?.data?.message || t("admin.impresoras.delete_error");
    toast(msg, "error");
  }
}

onMounted(async () => {
  if (window.bootstrap?.Modal && modalEl.value) {
    modalInstance = new window.bootstrap.Modal(modalEl.value);
  }
  await cargar();
});
</script>
