<template>
  <div class="space-y-6">
    <div>
      <h3 class="text-xl font-semibold mb-2">{{ i18n.exceptions_title }}</h3>
      <p class="text-sm text-gray-600">{{ i18n.exceptions_description }}</p>
    </div>

    <!-- Bug 61: warn when the last save closed dates that still had
         approved/pending bookings on them. The save itself goes through
         (provider may genuinely want to close the day and handle the
         bookings manually), but without this banner the bookings stay
         status='approved' while the calendar treats the day as closed
         — customer turns up to a closed business. -->
    <div
        v-if="Array.isArray(exceptionConflicts) && exceptionConflicts.length"
        class="bookaro-card p-4"
        style="border:1px solid #f59e0b;background:#fffbeb;"
        role="alert"
    >
      <div class="font-semibold mb-2" style="color:#92400e;">
        {{ i18n.exceptions_conflict_title || 'Existing bookings on closed dates' }}
      </div>
      <p class="text-sm mb-3" style="color:#92400e;">
        {{ i18n.exceptions_conflict_description
            || 'The dates you just closed still have these bookings. Cancel or reschedule them so customers know the appointment will not happen.' }}
      </p>
      <ul class="text-sm list-disc pl-5 space-y-1" style="color:#92400e;">
        <li v-for="c in exceptionConflicts" :key="c.id">
          <strong>#{{ c.id }}</strong>
          <span v-if="c.service_label"> &mdash; {{ c.service_label }}</span>
          <span v-if="c.status"> [{{ c.status }}]</span>
          <span v-if="c.booking_date">
            ({{ formatExceptionDate(String(c.booking_date).slice(0, 10)) }}<span
              v-if="c.booking_date_to && String(c.booking_date_to).slice(0, 10) !== String(c.booking_date).slice(0, 10)"
            >
              &rarr; {{ formatExceptionDate(String(c.booking_date_to).slice(0, 10)) }}</span>)
          </span>
        </li>
      </ul>
    </div>

    <div class="bookaro-settings-grid">
      <div class="bookaro-settings-section">
        <div class="bookaro-settings-section__title">{{ i18n.exceptions_range_title }}</div>
        <div class="bookaro-settings-section__desc">{{ i18n.exceptions_range_description }}</div>
        <div class="flex flex-wrap gap-3">
          <label class="text-sm">
            {{ i18n.exceptions_range_start }}
            <input type="date" v-model="rangeStart" class="bookaro-input mt-1 w-full text-sm" />
          </label>
          <label class="text-sm">
            {{ i18n.exceptions_range_end }}
            <input type="date" v-model="rangeEnd" class="bookaro-input mt-1 w-full text-sm" />
          </label>
        </div>
        <div class="mt-3 flex flex-wrap gap-2">
          <button
            type="button"
            @click="applyRange"
            class="bookaro-btn bookaro-btn--primary bookaro-btn--sm"
          >
            {{ i18n.exceptions_range_apply }}
          </button>
          <button
            type="button"
            @click="clearRange"
            class="bookaro-btn bookaro-btn--outline bookaro-btn--sm"
          >
            {{ i18n.exceptions_range_clear }}
          </button>
        </div>
        <p v-if="rangeMessage" class="text-sm mt-2" :class="rangeStatus === 'error' ? 'text-red-600' : 'text-green-600'">
          {{ rangeMessage }}
        </p>
      </div>

      <div class="bookaro-settings-section">
        <div class="bookaro-settings-section__title">{{ i18n.exceptions_calendar_title || i18n.exceptions_title }}</div>
        <div class="bookaro-settings-section__desc">{{ i18n.exceptions_calendar_description }}</div>
        <div class="max-w-sm mx-auto">
          <div class="flex items-center justify-between mb-2">
            <button type="button" @click="prevMonth" class="bookaro-btn bookaro-btn--ghost bookaro-btn--sm">&lsaquo;</button>
            <span class="font-medium">{{ monthLabel }}</span>
            <button type="button" @click="nextMonth" class="bookaro-btn bookaro-btn--ghost bookaro-btn--sm">&rsaquo;</button>
          </div>

          <div class="grid grid-cols-7 text-center text-sm text-gray-600 mb-1">
            <div v-for="day in weekdayHeaders" :key="day">{{ day }}</div>
          </div>

          <div class="grid grid-cols-7 gap-1">
            <button
              v-for="day in exceptionMonthDays"
              :key="day.format('YYYY-MM-DD')"
              type="button"
              @click="toggleException(day.format('YYYY-MM-DD'))"
              :disabled="isPast(day)"
              class="w-8 h-8 text-sm rounded-full focus:outline-none"
              :class="{
                'bg-red-500 text-white': sortedExceptionDates.includes(day.format('YYYY-MM-DD')),
                'text-gray-400': !day.isSame(exceptionMonth, 'month'),
                'opacity-50 cursor-not-allowed': isPast(day)
              }"
            >
              {{ day.date() }}
            </button>
          </div>
        </div>
      </div>
    </div>

    <div class="bookaro-settings-section">
      <div class="bookaro-settings-section__title">{{ i18n.exceptions_list_title }}</div>
      <div class="bookaro-settings-section__desc">{{ i18n.exceptions_list_description }}</div>

      <div v-if="!sortedExceptionDates.length" class="bookaro-exceptions-empty">
        {{ i18n.exceptions_empty_state }}
      </div>

      <div v-else class="flex flex-wrap gap-2">
        <span
          v-for="date in sortedExceptionDates"
          :key="date"
          class="bg-red-100 text-red-800 px-2 py-1 rounded-full text-sm flex items-center"
        >
          {{ formatExceptionDate(date) }}
          <button type="button" class="ml-1" @click="removeException(date)">&times;</button>
        </span>
      </div>
    </div>
  </div>
</template>

<script>
import dayjs from 'dayjs';

export default {
  name: 'ExceptionsTab',
  props: {
    i18n: { type: Object, required: true },
    exceptionDates: { type: Array, required: true },
    exceptionMonth: { type: Object, required: true },
    exceptionMonthDays: { type: Array, required: true },
    // Bug 61: array of {id, service_label, status, booking_date,
    // booking_date_to, closed_dates[]} returned from the most recent
    // save-settings AJAX call when the provider closed days that still
    // had pending/approved bookings on them.
    exceptionConflicts: { type: Array, default: () => [] }
  },
  data() {
    return {
      rangeStart: '',
      rangeEnd: '',
      rangeMessage: '',
      rangeStatus: 'success'
    };
  },
  computed: {
    weekdayHeaders() {
      return this.i18n.weekdays_short || [];
    },
    monthLabel() {
      const monthIdx = this.exceptionMonth.month();
      const fullMonth = Array.isArray(this.i18n.months) ? this.i18n.months[monthIdx] : '';
      const shortMonth = Array.isArray(this.i18n.months_short) ? this.i18n.months_short[monthIdx] : '';
      const year = String(this.exceptionMonth.year());
      const format = this.i18n.month_year_format || 'MMMM YYYY';
      let label = format;
      if (format.includes('MMMM')) {
        label = label.replace('MMMM', fullMonth || '');
      } else if (format.includes('MMM')) {
        label = label.replace('MMM', shortMonth || '');
      }
      label = label.replace('YYYY', year);
      return label.trim();
    },
    sortedExceptionDates() {
      return this.sortDates(this.exceptionDates || []);
    }
  },
  methods: {
    dayjs,
    isPast(day) {
      return day.isBefore(this.dayjs(), 'day');
    },
    sortDates(dates) {
      return [...new Set(dates)].sort();
    },
    emitDates(dates) {
      this.$emit('update:exceptionDates', this.sortDates(dates));
    },
    applyRange() {
      this.rangeMessage = '';
      const start = this.dayjs(this.rangeStart);
      const end = this.dayjs(this.rangeEnd);
      if (!start.isValid() || !end.isValid() || end.isBefore(start, 'day')) {
        this.rangeStatus = 'error';
        this.rangeMessage = this.i18n.exceptions_range_error;
        return;
      }

      const dates = this.buildRangeDates(start, end, true);
      this.emitDates([...(this.exceptionDates || []), ...dates]);
      this.rangeStatus = 'success';
      this.rangeMessage = this.i18n.exceptions_range_success;
    },
    clearRange() {
      this.rangeMessage = '';
      const start = this.dayjs(this.rangeStart);
      const end = this.dayjs(this.rangeEnd);
      if (!start.isValid() || !end.isValid() || end.isBefore(start, 'day')) {
        this.rangeStatus = 'error';
        this.rangeMessage = this.i18n.exceptions_range_error;
        return;
      }

      const dates = this.buildRangeDates(start, end, false);
      const filtered = (this.exceptionDates || []).filter((date) => !dates.includes(date));
      this.emitDates(filtered);
      this.rangeStatus = 'success';
      this.rangeMessage = this.i18n.exceptions_range_cleared;
    },
    buildRangeDates(start, end, skipPast) {
      const dates = [];
      const today = this.dayjs().startOf('day');
      let current = start.clone();
      while (current.isBefore(end, 'day') || current.isSame(end, 'day')) {
        if (!skipPast || !current.isBefore(today, 'day')) {
          dates.push(current.format('YYYY-MM-DD'));
        }
        current = current.add(1, 'day');
      }
      return dates;
    },
    toggleException(date) {
      if (this.isPast(this.dayjs(date))) {
        return;
      }

      if (this.sortedExceptionDates.includes(date)) {
        this.emitDates(this.sortedExceptionDates.filter((entry) => entry !== date));
        return;
      }

      this.emitDates([...this.sortedExceptionDates, date]);
    },
    removeException(date) {
      this.emitDates(this.sortedExceptionDates.filter((entry) => entry !== date));
    },
    formatExceptionDate(date) {
      const parsed = this.dayjs(date);
      const monthIdx = parsed.month();
      const monthName = Array.isArray(this.i18n.months_short) ? this.i18n.months_short[monthIdx] : '';
      const day = String(parsed.date());
      const year = String(parsed.year());
      if (!monthName) {
        return `${day} ${year}`.trim();
      }
      return `${monthName} ${day}, ${year}`;
    },
    nextMonth() {
      const updated = this.exceptionMonth.add(1, 'month');
      this.$emit('update:exceptionMonth', updated);
    },
    prevMonth() {
      const updated = this.exceptionMonth.subtract(1, 'month');
      this.$emit('update:exceptionMonth', updated);
    }
  }
};
</script>

<style scoped>
.bookaro-exceptions-empty {
  padding: 0.75rem;
  border: 1px dashed var(--bookaro-dashboard-border);
  border-radius: 0.75rem;
  color: var(--bookaro-dashboard-muted);
  font-size: 0.85rem;
  background: rgba(255, 255, 255, 0.5);
}
</style>
