<template>
  <div class="space-y-4">
    <div v-if="loading" class="flex justify-center py-16">
      <span class="loading loading-spinner loading-lg text-primary"></span>
    </div>

    <div v-else-if="error" class="text-center py-10 text-error">{{ error }}</div>

    <div v-else-if="data" class="space-y-6">
      <div class="flex flex-wrap items-center gap-x-4 gap-y-2">
        <h3 class="text-lg sm:text-xl font-bold">
          {{ data.nombre }} {{ data.segundo_nombre }} {{ data.apellido }}
        </h3>
        <span class="font-mono text-sm opacity-70">#{{ data.numero_voluntario }}</span>
        <span class="badge badge-sm" :class="badgeClass(data.status)">{{ data.status }}</span>
      </div>

      <section
        v-for="sec in sectionsWithData"
        :key="sec.key"
        class="rounded-box ring-1 ring-base-300 bg-base-100/60 overflow-hidden"
      >
        <h4 class="font-medium text-sm uppercase tracking-wide px-4 py-3 border-b border-base-200">
          {{ sec.title }}
        </h4>
        <dl class="divide-y divide-base-200/70 text-sm">
          <div
            v-for="f in sec.fields"
            :key="f.key"
            class="px-4 py-2.5 grid sm:grid-cols-[220px_1fr] gap-x-4 gap-y-1"
          >
            <dt class="text-base-content/60">{{ f.label }}</dt>
            <dd class="min-w-0 break-words">
              <div v-if="f.isList" :class="f.isLongList ? 'space-y-1.5' : 'flex flex-wrap gap-1.5'">
                <div
                  v-if="f.isLongList"
                  v-for="(item, i) in f.displayValues"
                  :key="'list-' + i"
                  class="text-sm border-l-2 border-base-300 pl-2"
                >
                  {{ item }}
                </div>
                <span
                  v-else
                  v-for="(item, i) in f.displayValues"
                  :key="'chip-' + i"
                  class="badge badge-sm badge-ghost border border-base-300 whitespace-normal text-left"
                >
                  {{ item }}
                </span>
              </div>
              <span v-else>{{ f.displayText }}</span>
            </dd>
          </div>
        </dl>
      </section>

      <section
        v-if="extraRows.length"
        class="rounded-box ring-1 ring-base-300 bg-base-100/60 overflow-hidden"
      >
        <h4 class="font-medium text-sm uppercase tracking-wide px-4 py-3 border-b border-base-200">
          Otros datos
        </h4>
        <dl class="divide-y divide-base-200/70 text-sm">
          <div
            v-for="r in extraRows"
            :key="r.rawKey"
            class="px-4 py-2.5 grid sm:grid-cols-[220px_1fr] gap-x-4 gap-y-1"
          >
            <dt class="text-base-content/60">{{ r.key }}</dt>
            <dd class="min-w-0 break-words">{{ r.value }}</dd>
          </div>
        </dl>
      </section>

      <section class="rounded-box ring-1 ring-base-300 bg-base-100/60 overflow-hidden">
        <h4 class="font-medium text-sm uppercase tracking-wide px-4 py-3 border-b border-base-200">
          Sistema
        </h4>
        <dl class="divide-y divide-base-200/70 text-sm">
          <div class="px-4 py-2.5 grid sm:grid-cols-[220px_1fr] gap-x-4 gap-y-1">
            <dt class="text-base-content/60">ID</dt>
            <dd class="font-mono break-all">{{ data.id }}</dd>
          </div>
          <div class="px-4 py-2.5 grid sm:grid-cols-[220px_1fr] gap-x-4 gap-y-1">
            <dt class="text-base-content/60">Versión de formulario</dt>
            <dd>{{ data.form_version || "—" }}</dd>
          </div>
          <div class="px-4 py-2.5 grid sm:grid-cols-[220px_1fr] gap-x-4 gap-y-1">
            <dt class="text-base-content/60">Correo enviado</dt>
            <dd>{{ formatDateTime(data.email_sent_at) }}</dd>
          </div>
          <div class="px-4 py-2.5 grid sm:grid-cols-[220px_1fr] gap-x-4 gap-y-1">
            <dt class="text-base-content/60">Registrado</dt>
            <dd>{{ formatDateTime(data.submitted_at) }}</dd>
          </div>
          <div class="px-4 py-2.5 grid sm:grid-cols-[220px_1fr] gap-x-4 gap-y-1">
            <dt class="text-base-content/60">Actualizado</dt>
            <dd>{{ formatDateTime(data.updated_at) }}</dd>
          </div>
        </dl>
      </section>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from "vue";
import { cachedFetch } from "../../lib/adminCache";

const props = defineProps({
  numero: { type: [Number, String], required: true },
});

const CORE_COLUMN_MAP = {
  nombre: "nombre",
  segundo_nombre: "segundo_nombre",
  apellido: "apellido",
  correo: "correo",
  fecha_nacimiento: "fecha_nacimiento",
  nacionalidad: "nacionalidad",
  sexo: "sexo",
  direccion_completa: "direccion",
  ciudad: "ciudad",
  estado: "estado",
  pais: "pais",
  postal: "codigo_postal",
  telefono: "telefono",
  whatsapp: "whatsapp",
  profesion: "profesion",
  lugar_trabajo_actual: "lugar_trabajo",
  nivel_academico: "nivel_academico",
};

const loading = ref(false);
const error = ref("");
const data = ref(null);
const sections = ref([]);

function pretty(v) {
  if (v === "si") return "Sí";
  if (v === "no") return "No";
  return v;
}

function fallbackLabel(key) {
  if (key.startsWith("idioma_nivel_")) return `Nivel de ${key.slice("idioma_nivel_".length)}`;
  if (key === "locale") return "Idioma de la solicitud";
  return key;
}

const respuestasByKey = computed(() => {
  const map = {};
  for (const r of data.value?.respuestas || []) {
    (map[r.key] ||= []).push(r.value);
  }
  return map;
});

function fieldTokens(field) {
  let values;
  if (field.key === "documentos") {
    const s = [data.value.documento_tipo, data.value.documento_nro].filter(Boolean).join(" ");
    values = s ? [s] : [];
  } else if (CORE_COLUMN_MAP[field.key]) {
    const v = data.value[CORE_COLUMN_MAP[field.key]];
    values = v === null || v === undefined || v === "" ? [] : [String(v)];
  } else {
    values = respuestasByKey.value[field.key] || [];
  }

  const tokens = [];
  for (const raw of values) {
    for (const part of String(raw).split(",")) {
      const tok = part.trim();
      if (!tok) continue;
      const opt = (field.options || []).find((o) => o.value === tok);
      let display = (opt ? opt.label : pretty(tok)).replace(/<[^>]*>/g, "");
      if (field.tipo === "date" || field.key === "fecha_nacimiento") {
        const d = new Date(display);
        if (!isNaN(d)) {
          display = d.toLocaleDateString("es", { year: "numeric", month: "2-digit", day: "2-digit" });
        }
      }
      tokens.push(display);
    }
  }
  return tokens;
}

const sectionsWithData = computed(() => {
  if (!data.value) return [];
  return sections.value
    .map((sec) => ({
      ...sec,
      fields: sec.fields
        .map((f) => {
          const tokens = fieldTokens(f);
          if (!tokens.length) return null;
          return {
            ...f,
            isList: f.tipo === "checkbox" && tokens.length > 1,
            isLongList: f.tipo === "checkbox" && tokens.length > 1 && tokens.some((t) => t.length > 40),
            displayValues: tokens,
            displayText: tokens.join(", "),
          };
        })
        .filter(Boolean),
    }))
    .filter((sec) => sec.fields.length);
});

const extraRows = computed(() => {
  if (!data.value) return [];
  const known = new Set();
  for (const sec of sections.value) for (const f of sec.fields) known.add(f.key);
  const rows = [];
  for (const [key, vals] of Object.entries(respuestasByKey.value)) {
    if (known.has(key)) continue;
    const tokens = [];
    for (const raw of vals) {
      for (const part of String(raw).split(",")) {
        const t = part.trim();
        if (t) tokens.push(pretty(t));
      }
    }
    if (!tokens.length) continue;
    rows.push({ key: fallbackLabel(key), rawKey: key, value: tokens.join(", ") });
  }
  return rows;
});

async function fetchData() {
  loading.value = true;
  error.value = "";
  try {
    const res = await cachedFetch(`/api/admin/voluntarios/${props.numero}`, { ttl: 60 });
    const json = await res.json();
    if (!json.success) throw new Error(json.message || "Voluntario no encontrado");
    data.value = json.data;
    sections.value = json.form.sections;
  } catch (e) {
    error.value = e.message;
  } finally {
    loading.value = false;
  }
}

watch(
  () => props.numero,
  () => {
    data.value = null;
    fetchData();
  }
);

function formatDateTime(iso) {
  if (!iso) return "—";
  const d = new Date(iso);
  if (isNaN(d)) return "—";
  return d.toLocaleString("es", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
  });
}

function badgeClass(s) {
  switch (s) {
    case "aprobado":
      return "badge-success";
    case "rechazado":
      return "badge-error";
    case "legacy":
      return "badge-warning";
    default:
      return "badge-neutral";
  }
}

onMounted(fetchData);
</script>
