<template>
  <div class="ade-agenda-container">
    <!-- Import ICS -->
    <div style="margin-bottom: 15px; text-align: center;">
      <input type="file" @change="handleFileUpload" accept=".ics" />
    </div>

    <!-- Le tableau ADE en haut, inchangé -->
    <table class="ade-table">
      <thead>
        <!-- 1ère ligne : Semaine + date de début -->
        <tr class="top-row">
          <th :colspan="daysOfWeek.length + 1" class="week-title">
            S{{ isoWeekNumber }} {{ formatDDMM(currentMonday) }}
          </th>
        </tr>

        <!-- 2e ligne : Horaire + 7 jours (jour + date + nom) -->
        <tr class="days-row">
          <th class="time-col-header">Horaire</th>
          <th
            v-for="(day, index) in daysOfWeek"
            :key="index"
            class="day-header"
          >
            <div class="day-label">
              {{ weekdayLabel(day) }} {{ formatDateShort(day) }}
            </div>
            <div class="resource-name">
              {{ resourceName }}
            </div>
          </th>
        </tr>
      </thead>

      <tbody>
        <tr v-for="(slot, slotIndex) in timeSlots" :key="slotIndex">
          <td class="time-col">{{ slot.start }} - {{ slot.end }}</td>
          <td
            v-for="(day, dayIndex) in daysOfWeek"
            :key="dayIndex"
            class="agenda-cell"
          >
            <div
              v-for="(evt, eIndex) in eventsForSlot(day, slot)"
              :key="eIndex"
              class="event-card"
              :style="eventStyle(evt)"
            >
              <div class="event-title">{{ evt.title }}</div>
              <div class="event-info">{{ evt.start }} - {{ evt.end }}</div>
            </div>
          </td>
        </tr>
      </tbody>
    </table>

    <div class="week-tabs">
      <button class="arrow-btn" @click="prevPage" :disabled="startIndex === 0">←</button>
      <button
        v-for="(week, idx) in displayedWeeks"
        :key="idx"
        class="week-tab-button"
        @click="goToWeek(week.monday)"
      >
        S{{ week.isoWeek }} {{ formatDDMM(week.monday) }}
      </button>
      <button
        class="arrow-btn"
        @click="nextPage"
        :disabled="startIndex + weeksToShow >= allWeeks.length"
      >
        →
      </button>
    </div>
  </div>
</template>

<script>
function getIsoWeekNumber(date) {
  const tempDate = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
  const dayNum = tempDate.getUTCDay() || 7;
  tempDate.setUTCDate(tempDate.getUTCDate() + 4 - dayNum);
  const yearStart = new Date(Date.UTC(tempDate.getUTCFullYear(), 0, 1));
  return Math.ceil(((tempDate - yearStart) / 86400000 + 1) / 7);
}

function formatDate(dateObj) {
  const yyyy = dateObj.getFullYear();
  const mm = String(dateObj.getMonth() + 1).padStart(2, "0");
  const dd = String(dateObj.getDate()).padStart(2, "0");
  return `${yyyy}-${mm}-${dd}`;
}

export default {
  name: "AdeLikeAgenda",
  data() {
    const currentMonday = new Date(2025, 2, 31);
    return {
      currentMonday,
      resourceName: "El Alaoui El Ismaili Omar",
      timeSlots: [
        { start: "08:00", end: "08:30" },
        { start: "08:30", end: "09:00" },
        { start: "09:00", end: "09:30" },
        { start: "09:30", end: "10:00" },
        { start: "10:00", end: "10:30" },
        { start: "10:30", end: "11:00" },
        { start: "11:00", end: "11:30" },
        { start: "11:30", end: "12:00" },
        { start: "12:00", end: "12:30" },
        { start: "12:30", end: "13:00" },
        { start: "13:00", end: "13:30" },
        { start: "13:30", end: "14:00" },
        { start: "14:00", end: "14:30" },
        { start: "14:30", end: "15:00" },
        { start: "15:00", end: "15:30" },
        { start: "15:30", end: "16:00" },
        { start: "16:00", end: "16:30" },
        { start: "16:30", end: "17:00" },
        { start: "17:00", end: "17:30" },
        { start: "17:30", end: "18:00" },
        { start: "18:00", end: "18:30" },
        { start: "18:30", end: "19:00" },
        { start: "19:00", end: "19:30" },
        { start: "19:30", end: "20:00" },
      ],
      events: [],
      allWeeks: [],
      weeksToShow: 7,
      startIndex: 0,
    };
  },
  computed: {
    daysOfWeek() {
      const result = [];
      for (let i = 0; i < 7; i++) {
        const d = new Date(this.currentMonday);
        d.setDate(d.getDate() + i);
        result.push(d);
      }
      return result;
    },
    isoWeekNumber() {
      return getIsoWeekNumber(this.currentMonday);
    },
    displayedWeeks() {
      return this.allWeeks.slice(this.startIndex, this.startIndex + this.weeksToShow);
    },
  },
  methods: {
    initWeeks() {
      const totalCount = 15;
      const baseDate = new Date(this.currentMonday);
      for (let i = 0; i < totalCount; i++) {
        const temp = new Date(baseDate);
        temp.setDate(baseDate.getDate() + i * 7);
        this.allWeeks.push({
          monday: temp,
          isoWeek: getIsoWeekNumber(temp),
        });
      }
    },
    eventsForSlot(dayDate, slot) {
      const dayStr = formatDate(dayDate);
      return this.events.filter(
        (evt) => evt.day === dayStr && evt.start === slot.start
      );
    },
    eventStyle(evt) {
      return {
        backgroundColor: evt.color || "#cef",
      };
    },
    formatDateShort(dateObj) {
      const dd = String(dateObj.getDate()).padStart(2, "0");
      const mm = String(dateObj.getMonth() + 1).padStart(2, "0");
      const yyyy = dateObj.getFullYear();
      return `${dd}/${mm}/${yyyy}`;
    },
    formatDDMM(dateObj) {
      const dd = String(dateObj.getDate()).padStart(2, "0");
      const mm = String(dateObj.getMonth() + 1).padStart(2, "0");
      return `${dd}/${mm}`;
    },
    weekdayLabel(dateObj) {
      const dayIndex = dateObj.getDay();
      const labels = [
        "Dimanche",
        "Lundi",
        "Mardi",
        "Mercredi",
        "Jeudi",
        "Vendredi",
        "Samedi",
      ];
      return labels[dayIndex];
    },
    goToWeek(mondayDate) {
      this.currentMonday = new Date(
        mondayDate.getFullYear(),
        mondayDate.getMonth(),
        mondayDate.getDate()
      );
    },
    prevPage() {
      if (this.startIndex > 0) this.startIndex--;
    },
    nextPage() {
      if (this.startIndex + this.weeksToShow < this.allWeeks.length) this.startIndex++;
    },

    // 💡 NOUVELLE MÉTHODE : lecture .ics
    handleFileUpload(event) {
      const file = event.target.files[0];
      if (!file) return;

      const reader = new FileReader();
      reader.onload = (e) => {
        const content = e.target.result;
        this.parseICS(content);
      };
      reader.readAsText(file);
    },

    parseICS(text) {
      const lines = text.split(/\r?\n/);
      let currentEvent = null;
      const events = [];

      for (const line of lines) {
        if (line === "BEGIN:VEVENT") {
          currentEvent = {};
        } else if (line === "END:VEVENT") {
          if (currentEvent) events.push(currentEvent);
          currentEvent = null;
        } else if (currentEvent) {
          if (line.startsWith("DTSTART")) {
            currentEvent.start = this.parseICSTime(line);
          } else if (line.startsWith("DTEND")) {
            currentEvent.end = this.parseICSTime(line);
          } else if (line.startsWith("SUMMARY")) {
            currentEvent.title = line.split(":")[1] || "Sans titre";
          }
        }
      }

      this.events = events.map((e) => ({
        title: e.title,
        day: e.start.date,
        start: e.start.time,
        end: e.end.time,
        color: "#acf",
      }));
    },

    parseICSTime(line) {
      const match = line.match(/:(\d{8})T(\d{4})/);
      if (!match) return { date: "", time: "" };

      const dateStr = match[1];
      const timeStr = match[2];
      return {
        date: `${dateStr.slice(0, 4)}-${dateStr.slice(4, 6)}-${dateStr.slice(6, 8)}`,
        time: `${timeStr.slice(0, 2)}:${timeStr.slice(2, 4)}`,
      };
    },
  },
  mounted() {
    this.initWeeks();
  },
};
</script>

<style scoped>
.ade-agenda-container {
  font-family: Arial, sans-serif;
  max-width: 1200px;
  margin: 0 auto;
}

/* Tableau principal */
.ade-table {
  width: 100%;
  border-collapse: collapse;
  table-layout: fixed;
  margin-bottom: 10px;
  background-color: #fff;
  border: 1px solid #ccc;
}

.top-row .week-title {
  background-color: #cde;
  font-size: 1.1rem;
  padding: 8px;
  text-align: center;
  color: #333;
  border-bottom: 2px solid #bbb;
}

.days-row th {
  background-color: #eee;
  color: #333;
  border: 1px solid #ccc;
  padding: 4px;
  text-align: center;
  font-weight: normal;
}

.time-col-header {
  background-color: #ececec;
  font-weight: bold;
  width: 80px;
}

.day-header {
  width: calc((100% - 80px) / 7);
}

.day-label {
  font-weight: bold;
}

.resource-name {
  font-size: 0.85rem;
  color: #555;
  margin-top: 2px;
}

td {
  border: 1px solid #ccc;
  padding: 3px;
  vertical-align: top;
}

.time-col {
  background-color: #f8f8f8;
  text-align: center;
  font-size: 0.85rem;
  font-weight: bold;
  color: #333;
}

.agenda-cell {
  min-height: 40px;
}

/* Cartes d'événement */
.event-card {
  margin: 2px 0;
  padding: 4px;
  border: 1px solid #999;
  border-radius: 4px;
  font-size: 0.8rem;
}

.event-title {
  font-weight: bold;
  margin-bottom: 2px;
}

.event-info {
  font-size: 0.75rem;
  color: #555;
}

/* Barre d'onglets en bas */
.week-tabs {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
  margin-bottom: 20px;
}

.week-tab-button {
  padding: 4px 8px;
  border: 1px solid #666;
  background-color: #eee;
  cursor: pointer;
  border-radius: 4px;
  font-size: 0.8rem;
  min-width: 60px;
}

.week-tab-button:hover {
  background-color: #ccc;
}

.arrow-btn {
  padding: 4px 8px;
  border: 1px solid #666;
  background-color: #ddd;
  cursor: pointer;
  border-radius: 4px;
  font-size: 0.8rem;
}

.arrow-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}
</style>
