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

import Input from "@Holos/Form/Input.vue";
import MembershipChargeModal from "@App/MembershipChargeModal.vue";
import MembershipDetailModal from "@App/MembershipDetailModal.vue";
import MembershipListItem from "@App/MembershipListItem.vue";

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

const api = useApi();

const searching = ref(false);
const processingPayment = ref(false);
const curp = ref("");
const showAddChargeModal = ref(false);
const showMembershipModal = ref(false);
const selectedMembership = ref(null);

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

const memberData = ref(emptyMemberData());

const hasMemberships = computed(
  () => memberData.value.memberships && memberData.value.memberships.length > 0
);

function normalizeMember(model) {
  return {
    id: model.id,
    curp: model.curp,
    name: model.name,
    tutor: model.tutor,
    photo: model.photo,
    photo_url: model.photo_url,
    memberships: model.memberships || [],
  };
}

function clearMemberData({ preserveQuery = true } = {}) {
  memberData.value = emptyMemberData();
  selectedMembership.value = null;
  showAddChargeModal.value = false;
  showMembershipModal.value = false;

  if (!preserveQuery) {
    curp.value = "";
  }
}

async function searchMemberByCurp(searchCurp, { notify = true } = {}) {
  searching.value = true;

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

      if (notify) {
        if (memberData.value.memberships.length === 0) {
          Notify.warning("El miembro no tiene membresías registradas");
        } else {
          Notify.success("Miembro encontrado");
        }
      }
    },
    onFail: (error) => {
      Notify.warning(error.message || "No se encontró el miembro con ese CURP");
      clearMemberData();
    },
    onError: () => {
      Notify.error("Error al buscar el miembro");
      clearMemberData();
    },
  });

  searching.value = false;
}

async function handleSearch() {
  if (!curp.value.trim()) {
    Notify.warning("Por favor ingresa un CURP");
    return;
  }

  await searchMemberByCurp(curp.value.trim());
}

function openMembershipDetails(membership) {
  selectedMembership.value = membership;
  showMembershipModal.value = true;
}

function closeMembershipDetails() {
  showMembershipModal.value = false;
  selectedMembership.value = null;
}

function openAddChargeModal() {
  showAddChargeModal.value = true;
}

function closeAddChargeModal() {
  showAddChargeModal.value = false;
}

async function handlePayment({ quantity }) {
  if (!memberData.value.id || !selectedMembership.value) {
    Notify.warning("No hay una membresía seleccionada");
    return;
  }

  processingPayment.value = true;

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

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

      closeMembershipDetails();
      await searchMemberByCurp(curp.value.trim(), { notify: false });
    },
    onFail: (error) => {
      Notify.warning(error.message || "No se pudo procesar el pago");
    },
    onError: () => {
      Notify.error("Error al procesar el pago");
    },
  });

  processingPayment.value = false;
}

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

  await searchMemberByCurp(curp.value.trim(), { notify: false });
}
</script>

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

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

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

      <div class="grid grid-cols-1 gap-6 md:grid-cols-2">
        <div>
          <label class="mb-2 block text-sm font-medium text-gray-600">
            Fotografía
          </label>
          <div
            class="flex h-80 w-full items-center justify-center overflow-hidden rounded-lg bg-gray-200"
          >
            <img
              v-if="memberData.photo_url"
              :src="memberData.photo_url"
              :alt="memberData.name"
              class="h-80 w-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>

        <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
          />
          <div class="rounded-lg bg-primary/5 p-4">
            <p class="text-sm text-gray-600">Membresías encontradas</p>
            <p class="mt-1 text-2xl font-semibold text-primary">
              {{ memberData.memberships.length }}
            </p>
          </div>
        </div>
      </div>
    </div>

    <div
      v-if="memberData.id"
      class="m-3 max-w-auto rounded-xl bg-white p-6 shadow-lg"
    >
      <div class="mb-6 flex items-center justify-between gap-4">
        <div>
          <h3 class="text-xl font-semibold text-gray-800">Membresías</h3>
          <p class="text-sm text-gray-500">
            Haz clic en una membresía para ver el detalle.
          </p>
        </div>
        <button
          type="button"
          class="rounded-lg bg-primary px-4 py-2 text-sm font-semibold text-white transition hover:bg-primary/90"
          @click="openAddChargeModal"
        >
          Agregar cobro
        </button>
      </div>

      <div v-if="hasMemberships" class="space-y-4">
        <MembershipListItem
          v-for="membership in memberData.memberships"
          :key="membership.id"
          :membership="membership"
          @select="openMembershipDetails"
        />
      </div>

      <div
        v-else
        class="rounded-xl border border-dashed border-gray-300 bg-gray-50 p-8 text-center text-gray-500"
      >
        El miembro no tiene membresías registradas.
      </div>
    </div>

    <MembershipDetailModal
      :show="showMembershipModal"
      :membership="selectedMembership"
      :loading="processingPayment"
      @close="closeMembershipDetails"
      @pay="handlePayment"
    />

    <MembershipChargeModal
      :show="showAddChargeModal"
      :member-id="memberData.id"
      @close="closeAddChargeModal"
      @charged="handleChargeCreated"
    />
  </div>
</template>
