<script setup>
import { ref, computed } from "vue";
import { apiURL, useApi } from "@/services/Api.js";

import Input from "@Holos/Form/Input.vue";
import QRscan from "./QRscan.vue";

/** Eventos */
const emit = defineEmits(["cash-cut-found", "cash-cut-delivered"]);

/** Instancias */
const api = useApi();

/** Control de visibilidad del formulario */
const isFormOpen = ref(false);

/** Refs */
const qr_token = ref("");
const loading = ref(false);
const cashCutData = ref({
  id: "",
  closed_by: "",
  start_at: "",
  end_at: "",
  total_amount: 0,
  status: "",
  received_at: "",
  received_by: "",
  isReceived: false,
});

const statusTranslations = {
  undelivered: "Sin entregar",
  received: "Entregado",
};

const statusInSpanish = computed(() => {
  return (
    statusTranslations[cashCutData.value.status] || cashCutData.value.status
  );
});

const formattedStartDate = computed(() => {
  if (!cashCutData.value.start_at) return "";
  return cashCutData.value.start_at.slice(0, 16);
});

const formattedEndDate = computed(() => {
  if (!cashCutData.value.end_at) return "";
  return cashCutData.value.end_at.slice(0, 16);
});

const cashierName = computed(() => {
  return cashCutData.value.closed_by?.full_name || "N/A";
});

const formattedAmount = computed(() => {
  if (!cashCutData.value.total_amount) return "0.00";
  return `$${parseFloat(cashCutData.value.total_amount).toLocaleString(
    "es-MX",
    {
      minimumFractionDigits: 2,
      maximumFractionDigits: 2,
    }
  )}`;
});

/** Métodos */
const handleQRDetected = async (code) => {
  qr_token.value = code;
  await searchCashCut();
};

const searchCashCut = async () => {
  if (!qr_token.value.trim()) {
    Notify.warning("Por favor escanea un código QR o ingresa el token");
    return;
  }

  loading.value = true;

  await api.get(apiURL(`cash-cuts/find-by-qr-token`), {
    params: {
      qr_token: qr_token.value,
    },
    onSuccess: (response) => {
      const model = response.model;

      if (model.status === "received") {
        Notify.info("La caja ya ha sido entregada previamente");

        cashCutData.value = {
          id: model.id,
          closed_by: model.closed_by,
          start_at: model.start_at,
          end_at: model.end_at,
          total_amount: model.total_amount,
          status: model.status,
          received_at: model.received_at,
          received_by: model.received_by,
          isReceived: true,
        };

        return;
      }

      cashCutData.value = {
        id: model.id,
        closed_by: model.closed_by,
        start_at: model.start_at,
        end_at: model.end_at,
        total_amount: model.total_amount,
        status: model.status,
        received_at: model.received_at,
        received_by: model.received_by,
        isReceived: false,
      };

      Notify.success("Corte de caja encontrado");
      emit("cash-cut-found", cashCutData.value);
    },
    onFail: (error) => {
      Notify.warning(error.message || "No se encontró el corte de caja");
    },
    onError: (error) => {
      Notify.error("Error al buscar el corte de caja");
    },
  });

  loading.value = false;
};

const handleDelivery = async () => {
  if (!cashCutData.value.id) {
    Notify.warning("No hay corte de caja para entregar");
    return;
  }

  if (cashCutData.value.isReceived) {
    Notify.info("El corte de caja ya ha sido entregado");
    return;
  }

  await api.put(apiURL(`cash-cuts/${cashCutData.value.id}/mark-as-received`), {
    onSuccess: (data) => {
      Notify.success("Corte de caja entregado correctamente");
      cashCutData.value.status = "received";

      emit("cash-cut-delivered", cashCutData.value);

      cashCutData.value.isReceived = true;
      cashCutData.value.received_at = data.received_at;
      cashCutData.value.received_by = data.received_by;
    },
    onFail: (error) => {
      Notify.warning(error.message || "No se pudo entregar el corte de caja");
    },
    onError: () => {
      Notify.error("Error al entregar el corte de caja");
    },
  });

  loading.value = false;
};

const handleSearch = () => {
  searchCashCut();
};

const clearForm = () => {
  cashCutData.value = {
    id: null,
    closed_by: null,
    start_at: "",
    end_at: "",
    total_amount: 0,
    status: "",
    received_at: "",
    received_by: "",
    isReceived: false,
  };
  qr_token.value = "";
};
</script>

<template>
  <div class="mx-4 mt-4 mb-6">
    <!-- Botón para abrir el formulario -->
    <button
      v-if="!isFormOpen"
      @click="isFormOpen = true"
      class="w-full bg-primary hover:bg-primary/90 text-white font-semibold py-3 px-6 rounded-lg transition-all duration-200 shadow-md hover:shadow-lg flex items-center justify-center space-x-2"
    >
      <span class="text-2xl">+</span>
      <span>Buscar y Entregar Corte de Caja</span>
    </button>

    <!-- Formulario expandible -->
    <div v-if="isFormOpen" class="space-y-6">
      <div class="bg-white rounded-xl p-6 shadow-lg">
        <div class="flex justify-between items-center mb-4">
          <h3 class="text-xl font-semibold text-gray-800">
            Buscar Corte de Caja
          </h3>
          <button
            @click="isFormOpen = false"
            class="text-gray-400 hover:text-gray-600 transition-colors"
            title="Cerrar"
          >
            <span class="text-2xl">&times;</span>
          </button>
        </div>
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <!-- Scanner QR -->
        <div class="mb-6">
          <label class="block text-sm text-gray-600 font-medium mb-2">
            Escanear Código QR
          </label>
          <div class="w-full h-80 bg-gray-800 rounded-lg overflow-hidden">
            <QRscan v-model="qr_token" @qr-detected="handleQRDetected" />
          </div>
        </div>

        <!-- Input manual -->
        <div class="flex flex-col justify-center">
          <div class="mb-5">
            <Input
              v-model="qr_token"
              id="Token QR"
              type="text"
              placeholder="Ingrese el token del QR"
              @keyup.enter="handleSearch"
            />
          </div>

          <button
            @click="handleSearch"
            :disabled="loading"
            type="button"
            class="w-full bg-[#7a0b3a] hover:bg-[#68082e] text-white font-medium py-3.5 rounded-lg transition-colors disabled:opacity-50"
          >
            {{ loading ? "Buscando..." : "Buscar" }}
          </button>
        </div>
      </div>
    </div>

    <!-- Formulario con datos del corte -->
    <div v-if="cashCutData.id" class="bg-white rounded-xl p-6 shadow-lg">
      <h3 class="text-xl font-semibold mb-4 text-gray-800">
        Datos del Corte de Caja
      </h3>

      <div class="grid grid-cols-2 gap-4 mb-5">
        <Input
          :model-value="formattedStartDate"
          id="Fecha de inicio"
          type="datetime-local"
          disabled
        />
        <Input
          :model-value="formattedEndDate"
          id="Fecha de cierre"
          type="datetime-local"
          disabled
        />
      </div>

      <div class="mb-5">
        <Input :model-value="cashierName" id="Cajero" type="text" disabled />
      </div>

      <div class="mb-5">
        <Input
          :model-value="formattedAmount"
          id="Monto total"
          type="text"
          class="text-lg font-semibold"
          disabled
        />
      </div>

      <div class="mb-5">
        <Input
          :model-value="statusInSpanish"
          id="Estado"
          type="text"
          disabled
        />
      </div>

        <div class="space-y-6">
          <div v-if="cashCutData.isReceived">
            <button
              type="button"
              @click="clearForm"
              class="w-full bg-blue-600 hover:bg-blue-700 text-white font-medium py-3.5 rounded-lg transition-colors flex items-center justify-center gap-2"
            >
              Limpiar y buscar otro corte
            </button>
          </div>

          <!-- Botón recibir -->
          <div>
            <button
              type="button"
              @click="handleDelivery"
              :disabled="cashCutData.isReceived"
              :class="[
                'w-full font-medium py-3.5 rounded-lg transition-colors',
                cashCutData.isReceived
                  ? 'bg-gray-400 cursor-not-allowed'
                  : 'bg-green-700 hover:bg-green-600 text-white',
              ]"
            >
              Entregar Corte de Caja
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
