<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">
              <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="javascript:;">{{ $t("ventas.caja.breadcrumb_parent") }}</a></li>
                <li class="breadcrumb-item active">{{ $t("ventas.caja.breadcrumb_current") }}</li>
              </ol>
            </nav>
          </div>
        </li>
      </ul>
    </teleport>
    <div class="row layout-top-spacing">
      <div class="col-lg-6">
        <div class="panel lavanderia-panel p-4">
          <h4 class="mb-3">{{ $t("ventas.caja.title_state") }}</h4>
          <div v-if="cargandoEstado" class="text-center py-4"><div class="spinner-border text-primary"></div></div>
          <div v-else-if="caja" class="card bg-light">
            <div class="card-body">
              <p class="mb-1">
                <strong>{{ caja.nombre }}</strong> <span class="badge bg-success">{{ $t("ventas.caja.open_badge") }}</span>
              </p>
              <p class="mb-1">{{ $t("ventas.caja.initial_balance") }}: ${{ Number(caja.saldo_inicial).toFixed(2) }}</p>
              <p class="mb-3">{{ $t("ventas.caja.opened_at") }}: {{ formatFecha(caja.abierto_at) }}</p>

              <h6 class="text-muted text-uppercase small">{{ $t("ventas.caja.arqueo_title") }}</h6>
              <div class="mb-2">
                <label class="form-label">{{ $t("ventas.caja.cash_counted") }}</label>
                <input v-model.number="efectivoContado" type="number" step="0.01" min="0" class="form-control" />
                <small class="text-muted">{{ $t("ventas.caja.cash_counted_help") }}</small>
              </div>
              <div class="mb-3">
                <label class="form-label">{{ $t("ventas.caja.notes_close") }}</label>
                <textarea v-model="notasCierre" class="form-control" rows="2" :placeholder="$t('ventas.caja.notes_ph')"></textarea>
              </div>

              <button type="button" class="btn btn-warning w-100" :disabled="cortando" @click="cortarCaja">
                {{ cortando ? $t("ventas.caja.close_processing") : $t("ventas.caja.close_btn") }}
              </button>
            </div>
          </div>
          <div v-else class="card bg-light">
            <div class="card-body">
              <p class="text-muted mb-3">{{ $t("ventas.caja.no_caja") }}</p>
              <div class="mb-2">
                <label class="form-label">{{ $t("ventas.caja.name_label") }}</label>
                <input v-model="nombreCaja" class="form-control" :placeholder="$t('ventas.caja.name_ph')" />
              </div>
              <div class="mb-2">
                <label class="form-label">{{ $t("ventas.caja.initial_label") }}</label>
                <input v-model.number="saldoInicial" type="number" step="0.01" min="0" class="form-control" />
              </div>
              <button type="button" class="btn btn-success w-100" :disabled="abriendo" @click="abrirCaja">
                {{ abriendo ? $t("ventas.caja.opening") : $t("ventas.caja.open_btn") }}
              </button>
            </div>
          </div>
        </div>
      </div>

      <div v-if="caja" class="col-lg-6 mt-4 mt-lg-0">
        <div class="panel lavanderia-panel p-4">
          <h4 class="mb-3">{{ $t("ventas.caja.movements_title") }}</h4>
          <div v-if="cargandoMovs" class="text-center py-3"><div class="spinner-border text-primary"></div></div>
          <div v-else-if="!movimientos.length" class="text-muted small mb-3">{{ $t("ventas.caja.movements_empty") }}</div>
          <ul v-else class="list-group list-group-flush mb-3">
            <li v-for="m in movimientos" :key="m.id" class="list-group-item px-0 d-flex justify-content-between align-items-start">
              <div>
                <span class="badge" :class="m.tipo === 'ingreso' ? 'bg-success' : 'bg-danger'">
                  {{ m.tipo === "ingreso" ? $t("ventas.caja.movements_in") : $t("ventas.caja.movements_out") }}
                </span>
                <span class="ms-2">${{ Number(m.monto).toFixed(2) }}</span>
                <div v-if="m.motivo" class="small text-muted">{{ m.motivo }}</div>
              </div>
            </li>
          </ul>

          <div class="row g-2 align-items-end">
            <div class="col-sm-4">
              <label class="form-label">{{ $t("ventas.caja.movements_type") }}</label>
              <select v-model="movTipo" class="form-select">
                <option value="ingreso">{{ $t("ventas.caja.movements_in") }}</option>
                <option value="egreso">{{ $t("ventas.caja.movements_out") }}</option>
              </select>
            </div>
            <div class="col-sm-3">
              <label class="form-label">{{ $t("ventas.caja.movements_amount") }}</label>
              <input v-model.number="movMonto" type="number" step="0.01" min="0.01" class="form-control" />
            </div>
            <div class="col-sm-5">
              <label class="form-label">{{ $t("ventas.caja.movements_reason") }}</label>
              <input v-model="movMotivo" class="form-control" />
            </div>
          </div>
          <button type="button" class="btn btn-outline-primary mt-3" :disabled="guardandoMov" @click="registrarMovimiento">
            {{ guardandoMov ? $t("ventas.caja.movements_loading") : $t("ventas.caja.movements_add") }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import { ref, onMounted } from "vue";
import { useI18n } from "vue-i18n";
import * as CajaRepository from "@/repositories/CajaRepository";

const { t } = useI18n();
const caja = ref(null);
const cargandoEstado = ref(true);
const abriendo = ref(false);
const cortando = ref(false);
const nombreCaja = ref("");
const saldoInicial = ref(0);
const efectivoContado = ref(null);
const notasCierre = ref("");

const movimientos = ref([]);
const cargandoMovs = ref(false);
const guardandoMov = ref(false);
const movTipo = ref("ingreso");
const movMonto = ref(null);
const movMotivo = ref("");

function formatFecha(str) {
  if (!str) return "";
  try {
    return new Date(str).toLocaleString("es-MX");
  } catch {
    return str;
  }
}

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

async function cargarMovimientos() {
  if (!caja.value) {
    movimientos.value = [];
    return;
  }
  cargandoMovs.value = true;
  try {
    const res = await CajaRepository.getMovimientos();
    movimientos.value = Array.isArray(res?.data) ? res.data : [];
  } catch {
    movimientos.value = [];
  } finally {
    cargandoMovs.value = false;
  }
}

async function cargarEstado() {
  cargandoEstado.value = true;
  try {
    const res = await CajaRepository.getEstado();
    caja.value = res && res.data ? res.data : null;
  } catch {
    caja.value = null;
  } finally {
    cargandoEstado.value = false;
  }
}

async function abrirCaja() {
  abriendo.value = true;
  try {
    await CajaRepository.abrir({ nombre: nombreCaja.value || undefined, saldo_inicial: saldoInicial.value });
    showMessage(t("ventas.caja.open_ok"), "success");
    await cargarEstado();
    await cargarMovimientos();
  } catch (e) {
    showMessage(e.response?.data?.errors?.caja?.[0] || t("ventas.caja.open_error"), "error");
  } finally {
    abriendo.value = false;
  }
}

async function cortarCaja() {
  cortando.value = true;
  try {
    const payload = { solo_json: true };
    if (efectivoContado.value !== null && efectivoContado.value !== "" && !Number.isNaN(Number(efectivoContado.value))) {
      payload.efectivo_contado = Number(efectivoContado.value);
    }
    if (notasCierre.value && String(notasCierre.value).trim()) {
      payload.notas_cierre = String(notasCierre.value).trim();
    }
    const res = await CajaRepository.cortar(payload);
    showMessage(t("ventas.caja.close_ok"), "success");
    const d = res?.data;
    if (d && window.Swal) {
      window.Swal.fire({
        title: "Corte",
        html: t("ventas.caja.cut_summary", {
          ventas: Number(d.total_ventas || 0).toFixed(2),
          saldo: Number(d.saldo_final || 0).toFixed(2),
          esperado: Number(d.esperado_efectivo ?? 0).toFixed(2),
        }),
        icon: "success",
      });
    }
    efectivoContado.value = null;
    notasCierre.value = "";
    await cargarEstado();
  } catch (e) {
    showMessage(e.response?.data?.message || t("ventas.caja.close_error"), "error");
  } finally {
    cortando.value = false;
  }
}

async function registrarMovimiento() {
  const m = Number(movMonto.value);
  if (!m || m <= 0) {
    showMessage(t("ventas.caja.movements_error"), "error");
    return;
  }
  guardandoMov.value = true;
  try {
    await CajaRepository.storeMovimiento({
      tipo: movTipo.value,
      monto: m,
      motivo: movMotivo.value || undefined,
    });
    showMessage(t("ventas.caja.movements_ok"), "success");
    movMonto.value = null;
    movMotivo.value = "";
    await cargarMovimientos();
  } catch {
    showMessage(t("ventas.caja.movements_error"), "error");
  } finally {
    guardandoMov.value = false;
  }
}

onMounted(async () => {
  await cargarEstado();
  await cargarMovimientos();
});
</script>
