<template>
  <q-page class="mail-debug-page">
    <div class="mail-debug-shell">
      <header class="mail-debug-header">
        <p class="eyebrow">Developer tools</p>
        <h1>Mail Debug</h1>
        <p class="subtitle">
          Seleziona una mail da <strong>/maildebug</strong> e visualizza l'HTML renderizzato.
        </p>
      </header>

      <q-card flat bordered class="mail-debug-card">
        <q-card-section class="controls">
          <q-btn
            color="primary"
            icon="refresh"
            label="Aggiorna lista"
            :loading="loading"
            @click="loadMails"
          />

          <q-select
            v-model="selectedIndex"
            :options="mailOptions"
            option-label="label"
            option-value="value"
            emit-value
            map-options
            outlined
            dense
            label="Seleziona mail"
            class="mail-select"
            :disable="loading || mails.length === 0"
          />
        </q-card-section>

        <q-separator />

        <q-card-section>
          <div v-if="errorMessage" class="error-box">
            {{ errorMessage }}
          </div>

          <div v-else-if="!selectedMail" class="empty-state">Nessuna mail selezionata.</div>

          <div v-else class="preview-grid">
            <div class="meta-column">
              <p class="meta-label">Nome mail</p>
              <h2>{{ selectedMailParsed.displayName }}</h2>
              <p v-if="selectedMailParsed.email" class="meta-line">
                <strong>Email:</strong> {{ selectedMailParsed.email }}
              </p>
              <p v-if="selectedMailParsed.localDate" class="meta-line">
                <strong>Data locale:</strong> {{ selectedMailParsed.localDate }}
              </p>
              <q-btn
                flat
                color="secondary"
                icon="content_copy"
                label="Copia HTML"
                @click="copyHtml"
              />
            </div>

            <div class="preview-column">
              <p class="meta-label">Render HTML</p>
              <iframe
                class="preview-frame"
                :srcdoc="selectedMailSrcDoc"
                sandbox="allow-popups allow-popups-to-escape-sandbox"
                title="Mail HTML preview"
              />
            </div>
          </div>
        </q-card-section>
      </q-card>
    </div>
  </q-page>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import { useQuasar } from 'quasar';
import { mailDebug, type MailDebugItem } from 'src/api/api';

const $q = useQuasar();

const loading = ref(false);
const mails = ref<MailDebugItem[]>([]);
const selectedIndex = ref<number | null>(null);
const errorMessage = ref('');

const mailOptions = computed(() => {
  return mails.value.map((mail, index) => ({
    label: parseMailName(mail.name || `Mail ${index + 1}`).displayName,
    value: index,
  }));
});

const selectedMail = computed<MailDebugItem | null>(() => {
  if (selectedIndex.value === null) {
    return null;
  }

  return mails.value[selectedIndex.value] ?? null;
});

const selectedMailParsed = computed(() => {
  if (!selectedMail.value) {
    return {
      displayName: '',
      email: null as string | null,
      localDate: null as string | null,
    };
  }

  return parseMailName(selectedMail.value.name);
});

const selectedMailSrcDoc = computed(() => {
  return injectBaseTargetBlank(selectedMail.value?.content ?? '');
});

function injectBaseTargetBlank(html: string): string {
  const baseTag = '<base target="_blank" rel="noopener noreferrer">';

  if (/<base\s/i.test(html)) {
    return html;
  }

  if (/<head[^>]*>/i.test(html)) {
    return html.replace(/<head[^>]*>/i, (match) => `${match}${baseTag}`);
  }

  return `${baseTag}${html}`;
}

function parseMailName(rawName: string): {
  displayName: string;
  email: string | null;
  localDate: string | null;
} {
  const withoutExtension = rawName.replace(/\.eml$/i, '');
  const prefixedTimestampMatch = withoutExtension.match(/^(\d{10,20})_(.+)$/);

  let sourceForEmail = withoutExtension;
  let timestampRaw: string | null = null;

  if (prefixedTimestampMatch?.[1] && prefixedTimestampMatch[2]) {
    timestampRaw = prefixedTimestampMatch[1];
    sourceForEmail = prefixedTimestampMatch[2];
  }

  const normalizedEmailSource = sourceForEmail.replace(/_at_/gi, '@');
  const emailMatch = normalizedEmailSource.match(/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/);

  const localDateFromEpoch = timestampRaw ? formatEpochToLocale(timestampRaw) : null;

  const localDate = localDateFromEpoch ?? extractLocalDate(withoutExtension);
  const displayName = emailMatch?.[0] ?? normalizedEmailSource;

  return {
    displayName,
    email: emailMatch ? emailMatch[0] : null,
    localDate,
  };
}

function formatEpochToLocale(rawEpoch: string): string | null {
  const epochNum = Number(rawEpoch);
  if (!Number.isFinite(epochNum)) {
    return null;
  }

  let milliseconds = epochNum;

  if (rawEpoch.length >= 19) {
    milliseconds = Math.floor(epochNum / 1_000_000);
  } else if (rawEpoch.length >= 16) {
    milliseconds = Math.floor(epochNum / 1_000);
  } else if (rawEpoch.length <= 10) {
    milliseconds = epochNum * 1_000;
  }

  const date = new Date(milliseconds);
  if (Number.isNaN(date.getTime())) {
    return null;
  }

  return date.toLocaleString();
}

function extractLocalDate(value: string): string | null {
  const isoMatch = value.match(/(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z?)/);
  if (isoMatch) {
    return formatDateCandidate(isoMatch[0]);
  }

  const plainMatch = value.match(/(\d{4}-\d{2}-\d{2}[ _]\d{2}[-:]\d{2}[-:]\d{2})/);
  if (plainMatch) {
    return formatDateCandidate(plainMatch[0]);
  }

  return null;
}

function formatDateCandidate(value: string): string {
  const normalized = value.replace(' ', 'T').replace(/(T\d{2})-(\d{2})-(\d{2})$/, '$1:$2:$3');

  const date = new Date(normalized);
  if (Number.isNaN(date.getTime())) {
    return value;
  }

  return date.toLocaleString();
}

async function loadMails(): Promise<void> {
  loading.value = true;
  errorMessage.value = '';

  try {
    const response = await mailDebug();

    if (response.error) {
      errorMessage.value = response.error;
      mails.value = [];
      selectedIndex.value = null;
      return;
    }

    mails.value = Array.isArray(response.data) ? response.data : [];
    selectedIndex.value = mails.value.length > 0 ? 0 : null;
  } catch (error) {
    errorMessage.value = error instanceof Error ? error.message : String(error);
    mails.value = [];
    selectedIndex.value = null;
  } finally {
    loading.value = false;
  }
}

async function copyHtml(): Promise<void> {
  if (!selectedMail.value) {
    return;
  }

  try {
    await navigator.clipboard.writeText(selectedMail.value.content);
    $q.notify({
      type: 'positive',
      message: 'HTML copiato negli appunti',
      position: 'top-right',
    });
  } catch {
    $q.notify({
      type: 'negative',
      message: 'Copia non riuscita',
      position: 'top-right',
    });
  }
}

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

<style scoped>
.mail-debug-page {
  min-height: 100vh;
  background:
    radial-gradient(circle at 12% 10%, #fde9d5 0%, transparent 30%),
    radial-gradient(circle at 86% 18%, #d9f5ee 0%, transparent 35%),
    linear-gradient(140deg, #f8f4ed 0%, #edf8f7 100%);
  padding: 24px 16px 32px;
}

.mail-debug-shell {
  max-width: 1300px;
  margin: 0 auto;
}

.mail-debug-header {
  margin-bottom: 16px;
}

.eyebrow {
  margin: 0;
  letter-spacing: 0.18em;
  text-transform: uppercase;
  color: #375266;
  font-size: 11px;
  font-weight: 700;
}

.mail-debug-header h1 {
  margin: 4px 0;
  font-family: 'Space Grotesk', sans-serif;
  font-size: clamp(1.6rem, 2.8vw, 2.3rem);
}

.subtitle {
  margin: 0;
  color: #4f6676;
}

.mail-debug-card {
  border-radius: 14px;
  background: rgba(255, 255, 255, 0.8);
}

.controls {
  display: flex;
  gap: 12px;
  align-items: center;
  flex-wrap: wrap;
}

.mail-select {
  min-width: 280px;
  flex: 1;
}

.preview-grid {
  display: grid;
  grid-template-columns: 290px 1fr;
  gap: 16px;
}

.meta-column {
  background: #f2f7fb;
  border: 1px solid #d7e5f1;
  border-radius: 12px;
  padding: 14px;
}

.meta-label {
  margin: 0;
  text-transform: uppercase;
  letter-spacing: 0.1em;
  font-size: 11px;
  color: #5d7586;
}

.meta-column h2 {
  margin: 8px 0 16px;
  font-size: 1.2rem;
  word-break: break-word;
}

.meta-line {
  margin: 0 0 10px;
  color: #4a6171;
  word-break: break-word;
}

.preview-column {
  min-width: 0;
}

.preview-frame {
  width: 100%;
  min-height: 68vh;
  border: 1px solid #d8e2ea;
  border-radius: 12px;
  background: #ffffff;
}

.empty-state,
.error-box {
  border-radius: 10px;
  padding: 12px;
}

.empty-state {
  background: #edf3f8;
  color: #5b7080;
}

.error-box {
  background: #fdeceb;
  color: #9f2b2b;
}

@media (max-width: 860px) {
  .preview-grid {
    grid-template-columns: 1fr;
  }

  .preview-frame {
    min-height: 55vh;
  }
}
</style>
