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

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

/** Eventos */
const emit = defineEmits(["membership-paid"]);

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

/** Refs */
const loading = ref(false);
const curp = ref("");

const memberData = ref({
  id: null,
  curp: "",
  name: "",
  tutor: null,
  photo: "",
  photo_url: "",
  memberships: [],
});

const paymentData = ref({
  membershipId: null,
  quantity: 1,
  totalAmount: 0,
});

/** Computed */
const activeMembership = computed(() => {
  if (
    !memberData.value.memberships ||
    memberData.value.memberships.length === 0
  ) {
    return null;
  }
  return memberData.value.memberships[0];
});

const expiresAt = computed(() => {
  if (!activeMembership.value || !activeMembership.value.expires_at)
    return null;
  const date = new Date(activeMembership.value.expires_at);
  return date.toLocaleDateString("es-MX", {
    year: "numeric",
    month: "long",
    day: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  });
});

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

/** Métodos */
const handleSearch = async () => {
  if (!curp.value.trim()) {
    Notify.warning("Por favor ingresa un CURP");
    return;
  }

  loading.value = true;

  await api.get(apiURL("members/search"), {
    params: {
      curp: curp.value,
    },
    onSuccess: (response) => {
      const model = response.model;

      memberData.value = {
        id: model.id,
        curp: model.curp,
        name: model.name,
        tutor: model.tutor,
        photo: model.photo,
        photo_url: model.photo_url,
        memberships: model.memberships || [],
      };

      if (memberData.value.memberships.length === 0) {
        Notify.warning("El miembro no tiene membresías activas");
      } else {
        Notify.success("Miembro encontrado");

        // Pre-cargar datos del pago
        if (activeMembership.value) {
          paymentData.value.membershipId = activeMembership.value.id;
          calculateTotal();
        }
      }
    },
    onFail: (error) => {
      Notify.warning(error.message || "No se encontró el miembro con ese CURP");
      clearMemberData();
    },
    onError: () => {
      Notify.error("Error al buscar el miembro");
      clearMemberData();
    },
  });

  loading.value = false;
};

const calculateTotal = () => {
  if (!activeMembership.value) {
    paymentData.value.totalAmount = 0;
    return;
  }

  const unitCost = parseFloat(
    activeMembership.value.charge_concept.unit_cost_peso || 0
  );
  const quantity = parseInt(paymentData.value.quantity) || 1;

  paymentData.value.totalAmount = unitCost * quantity;
};

const handlePayment = async () => {
  if (!memberData.value.id) {
    Notify.warning("Primero debes buscar un miembro");
    return;
  }

  if (!activeMembership.value) {
    Notify.warning("El miembro no tiene membresías activas para pagar");
    return;
  }

  if (paymentData.value.totalAmount <= 0) {
    Notify.warning("El monto debe ser mayor a 0");
    return;
  }

  loading.value = true;

  await api.put(apiURL(`members/${memberData.value.id}/charge-membership`), {
    data: {
      charge_concept_id: activeMembership.value.charge_concept.id,
      quantity: paymentData.value.quantity,
    },
    onSuccess: (response) => {
      Notify.success("Pago de membresía procesado correctamente");

      // Actualizar la membresía con la nueva info
      if (response.membership) {
        memberData.value.memberships = [response.membership];
      }

      emit("membership-paid", {
        member: response.member,
        membership: response.membership,
        payment: response.payment,
      });

      clearMemberData();
    },
    onFail: (error) => {
      Notify.warning(error.message || "No se pudo procesar el pago");
    },
    onError: () => {
      Notify.error("Error al procesar el pago");
    },
  });

  loading.value = false;
};

const isMembershipActive = computed(() => {
  if (!activeMembership.value || !activeMembership.value.expires_at)
    return false;

  const expirationDate = new Date(activeMembership.value.expires_at);
  const now = new Date();

  return expirationDate > now;
});

// Computed para mostrar días restantes
const daysUntilExpiration = computed(() => {
  if (!activeMembership.value || !activeMembership.value.expires_at)
    return null;

  const expirationDate = new Date(activeMembership.value.expires_at);
  const now = new Date();
  const diffTime = expirationDate - now;
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

  return diffDays > 0 ? diffDays : 0;
});

const clearMemberData = () => {
  memberData.value = {
    id: null,
    curp: "",
    name: "",
    tutor: null,
    photo: "",
    photo_url: "",
    memberships: [],
  };
  paymentData.value = {
    membershipId: null,
    quantity: 1,
    totalAmount: 0,
  };
  curp.value = "";
};
</script>

<template>
  <div class="p-6">
    <!-- Formulario de búsqueda -->
    <div class="bg-white rounded-xl p-6 m-3 max-w-auto shadow-lg mb-6">
      <h3 class="text-xl font-semibold mb-6 text-gray-800">Buscar miembro</h3>
      <form @submit.prevent="handleSearch">
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4 items-end">
          <!-- CURP -->
          <Input
            v-model="curp"
            id="CURP"
            type="text"
            placeholder="Ej: AMWO0020923"
            :disabled="loading"
          />

          <!-- Botón Buscar -->
          <button
            type="submit"
            :disabled="loading"
            class="py-3 px-8 rounded-lg transition-colors h-[42px] bg-[#7a0b3a] hover:bg-[#68082e] text-white font-medium disabled:opacity-50"
          >
            {{ loading ? "Buscando..." : "Buscar" }}
          </button>
        </div>
      </form>
    </div>

    <!-- Información del Miembro -->
    <div
      v-if="memberData.id"
      class="bg-white rounded-xl p-6 m-3 max-w-auto shadow-lg mb-6"
    >
      <h3 class="text-xl font-semibold mb-6 text-gray-800">
        Información del Miembro
      </h3>

      <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
        <!-- Fotografía -->
        <div>
          <label class="block text-sm text-gray-600 font-medium mb-2">
            Fotografía
          </label>
          <div
            class="w-full h-80 bg-gray-200 rounded-lg flex items-center justify-center overflow-hidden"
          >
            <img
              v-if="memberData.photo_url"
              :src="memberData.photo_url"
              :alt="memberData.name"
              class="w-80 h-80 object-cover"
            />
            <svg
              v-else
              xmlns="http://www.w3.org/2000/svg"
              class="h-24 w-24 text-gray-400"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
            >
              <path
                stroke-linecap="round"
                stroke-linejoin="round"
                stroke-width="2"
                d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"
              />
            </svg>
          </div>
        </div>

        <!-- Datos del miembro -->
        <div class="space-y-5">
          <Input
            :model-value="memberData.name"
            id="Nombre"
            type="text"
            disabled
          />

          <Input
            :model-value="memberData.curp"
            id="CURP"
            type="text"
            disabled
          />

          <Input
            :model-value="memberData.tutor || 'Sin tutor'"
            id="Nombre Tutor"
            type="text"
            disabled
          />

          <!-- Información de membresía -->
          <div v-if="activeMembership" class="space-y-3">
            <div class="p-4 bg-blue-50 rounded-lg">
              <p class="text-sm text-gray-600">Tipo de membresía:</p>
              <p class="text-lg font-semibold text-gray-800">
                {{ activeMembership.charge_concept.name }}
              </p>
            </div>

            <div v-if="expiresAt" class="p-4 bg-yellow-50 rounded-lg">
              <p class="text-sm text-gray-600">Expira:</p>
              <p class="text-lg font-semibold text-gray-800">{{ expiresAt }}</p>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Realizar Cobro de Membresía -->
    <div
      v-if="memberData.id && activeMembership"
      class="bg-white rounded-xl p-6 m-3 max-w-auto shadow-lg"
    >
      <h3 class="text-xl font-semibold mb-6 text-gray-800">
        Realizar Cobro de Membresía
      </h3>

      <form @submit.prevent="handlePayment">
        <div class="grid grid-cols-3 gap-4 mb-6">
          <!-- Servicio -->
          <div>
            <Input
              :model-value="activeMembership.charge_concept.name"
              id="Servicio"
              type="text"
              disabled
            />
            <p class="text-xs text-gray-500 mt-1">
              Costo unitario: ${{
                activeMembership.charge_concept.unit_cost_peso
              }}
            </p>
          </div>

          <!-- Cantidad -->
          <Input
            v-model.number="paymentData.quantity"
            id="Cantidad"
            type="number"
            min="1"
            :disabled="loading"
            @input="calculateTotal"
          />

          <!-- Monto Total -->
          <Input
            :model-value="formattedAmount"
            id="Monto Total"
            type="text"
            disabled
          />
        </div>

        <!-- Información de membresía -->
        <div v-if="activeMembership" class="space-y-3">
          <!-- Badge de estado de membresía -->
          <div
            :class="[
              'p-4 rounded-lg border-2',
              isMembershipActive
                ? 'bg-green-50 border-green-500'
                : 'bg-red-50 border-red-500',
            ]"
          >
            <p
              class="text-sm font-semibold"
              :class="isMembershipActive ? 'text-green-700' : 'text-red-700'"
            >
              {{
                isMembershipActive
                  ? "✓ Membresía activa"
                  : "✗ Membresía vencida"
              }}
            </p>
            <p
              v-if="isMembershipActive && daysUntilExpiration"
              class="text-xs mt-1"
              :class="
                daysUntilExpiration <= 7 ? 'text-orange-600' : 'text-green-600'
              "
            >
              {{
                daysUntilExpiration === 1
                  ? "Vence mañana"
                  : `Vence en ${daysUntilExpiration} días`
              }}
            </p>
          </div>

          <div class="p-4 bg-blue-50 rounded-lg">
            <p class="text-sm text-gray-600">Tipo de membresía:</p>
            <p class="text-lg font-semibold text-gray-800">
              {{ activeMembership.charge_concept.name }}
            </p>
          </div>

          <div v-if="expiresAt" class="p-4 bg-yellow-50 rounded-lg">
            <p class="text-sm text-gray-600">
              {{ isMembershipActive ? "Expira:" : "Expiró:" }}
            </p>
            <p class="text-lg font-semibold text-gray-800">{{ expiresAt }}</p>
          </div>
        </div>

        <!-- Botón de pago -->
        <button
          type="submit"
          :disabled="loading || !activeMembership || isMembershipActive"
          class="w-full bg-green-700 hover:bg-green-600 text-white font-medium py-3.5 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
        >
          {{
            loading
              ? "Procesando..."
              : isMembershipActive
              ? "Membresía activa - No requiere pago"
              : "Renovar membresía"
          }}
        </button>
      </form>
    </div>
  </div>
</template>
