<template>
  <div
    v-if="show"
    class="bookaro-booking-modal"
    @click.self="close"
  >
    <div class="bookaro-booking-wrapper bookaro-reschedule-wrapper bookaro-card">
      <div v-if="saving" class="modal-loader">
        <div class="spinner"></div>
      </div>

      <button class="modal-close-button" @click="close">&times;</button>

      <div class="step-header">
        <h3 class="step-title">{{ modalTitle }}</h3>
      </div>

      <template v-if="!hasOutcome">
        <div class="bookaro-reschedule-summary">
          <div class="bookaro-reschedule-row">
            <span class="bookaro-reschedule-label">{{ i18n.service_name }}</span>
            <span class="bookaro-reschedule-value">
              {{ booking && booking.service_label ? booking.service_label : fallbackDash }}
            </span>
          </div>
          <div class="bookaro-reschedule-row">
            <span class="bookaro-reschedule-label">{{ i18n.current_date }}</span>
            <span class="bookaro-reschedule-value">
              {{ formatDateRange(booking ? booking.booking_date : '', booking ? booking.booking_date_to : '') }}
            </span>
          </div>
          <div v-if="bookingStatusLabel" class="bookaro-reschedule-row">
            <span class="bookaro-reschedule-label">{{ i18n.action_status_label || 'Current status' }}</span>
            <span class="bookaro-reschedule-value">{{ bookingStatusLabel }}</span>
          </div>
        </div>

        <section
          v-if="showPolicy"
          class="bookaro-policy-panel"
          :class="{ 'is-blocked': !policy.allowed }"
        >
          <h4 class="details-section-title">{{ i18n.policy_status_title || i18n.policy_title || 'Action windows' }}</h4>
          <p v-if="policy.summary" class="bookaro-policy-summary">{{ policy.summary }}</p>
          <div v-if="policy.why" class="bookaro-policy-copy">
            <span class="bookaro-policy-copy__label">{{ i18n.policy_why_label || 'Why it matters' }}</span>
            <span>{{ policy.why }}</span>
          </div>
          <div v-if="policy.next" class="bookaro-policy-copy">
            <span class="bookaro-policy-copy__label">{{ i18n.policy_next_label || 'What to do next' }}</span>
            <span>{{ policy.next }}</span>
          </div>
        </section>

        <div class="bookaro-field-group">
          <label class="bookaro-policy-copy__label" for="bookaro-cancel-reason">
            {{ i18n.cancel_reason_title }}
          </label>
          <textarea
            id="bookaro-cancel-reason"
            v-model="reason"
            rows="4"
            class="bookaro-textarea w-full"
            :placeholder="i18n.cancel_reason_placeholder || i18n.enter_note"
          ></textarea>
        </div>

        <div v-if="error" class="bookaro-policy-error">
          {{ error }}
        </div>

        <div class="reschedule-actions">
          <button
            @click="close"
            class="bookaro-btn bookaro-btn--outline"
            type="button"
          >
            {{ i18n.action_close || i18n.close || i18n.cancel }}
          </button>
          <button
            @click="submit"
            :disabled="saving || !policy.allowed"
            class="bookaro-btn bookaro-btn--primary"
            type="button"
          >
            <span v-if="saving">{{ i18n.saving || i18n.saving_label }}</span>
            <span v-else>{{ i18n.cancel_booking_confirm || i18n.cancel }}</span>
          </button>
        </div>
      </template>

      <template v-else>
        <section class="bookaro-policy-panel is-success">
          <h4 class="details-section-title">{{ i18n.action_outcome_title || 'What changed' }}</h4>
          <p v-if="outcome.summary" class="bookaro-policy-summary">{{ outcome.summary }}</p>
          <ul v-if="outcome.details.length" class="details-policy-list">
            <li v-for="(line, idx) in outcome.details" :key="`cancel-outcome-${idx}`">
              {{ line }}
            </li>
          </ul>
        </section>

        <div class="reschedule-actions">
          <button
            @click="close"
            class="bookaro-btn bookaro-btn--primary"
            type="button"
          >
            {{ i18n.action_done || i18n.close }}
          </button>
        </div>
      </template>
    </div>
  </div>
</template>

<script>
import { restRequest } from '@bookaro-free/js/rest';
import { getActionPolicy, getOutcomeModel } from '@bookaro-free/utils/bookingPolicies.js';

export default {
  name: 'CancelBookingModal',
  props: {
    show: { type: Boolean, default: false },
    booking: { type: Object, default: null },
    i18n: { type: Object, default: () => ({}) }
  },
  data() {
    return {
      reason: '',
      saving: false,
      error: '',
      responsePayload: null
    };
  },
  computed: {
    fallbackDash() {
      return this.i18n.placeholder_dash || '-';
    },
    policy() {
      return getActionPolicy(this.booking, 'cancel');
    },
    outcome() {
      return getOutcomeModel(this.responsePayload);
    },
    hasOutcome() {
      return !!(this.outcome.title || this.outcome.summary || this.outcome.details.length);
    },
    showPolicy() {
      return !!(this.policy.summary || this.policy.why || this.policy.next);
    },
    modalTitle() {
      return this.hasOutcome
        ? (this.outcome.title || this.i18n.cancel_booking_title || this.i18n.cancel_reason_title)
        : (this.i18n.cancel_booking_title || this.i18n.cancel_reason_title);
    },
    bookingStatusLabel() {
      const status = (this.booking?.policy_snapshot?.status_label || this.booking?.status || '').toString().trim();
      if (!status) {
        return '';
      }
      const normalized = status.toLowerCase();
      const map = {
        pending: this.i18n.status_pending || this.i18n.pending,
        approved: this.i18n.status_approved || this.i18n.approved,
        rejected: this.i18n.status_rejected || this.i18n.rejected,
        cancelled: this.i18n.status_cancelled || this.i18n.cancelled,
        completed: this.i18n.status_completed || this.i18n.completed,
        no_show: this.i18n.status_no_show || this.i18n.no_show
      };
      return map[normalized] || status;
    }
  },
  watch: {
    show(value) {
      if (value) {
        this.resetState();
      }
    },
    booking() {
      if (this.show) {
        this.resetState();
      }
    }
  },
  methods: {
    resetState() {
      this.reason = this.booking?.cancel_reason || '';
      this.saving = false;
      this.error = '';
      this.responsePayload = null;
    },
    submit() {
      if (!this.booking || this.saving || !this.policy.allowed) {
        return;
      }

      this.saving = true;
      this.error = '';

      restRequest(`bookaro/v1/bookings/${this.booking.id}/cancel`, {
        method: 'POST',
        data: { cancel_reason: this.reason.trim() }
      })
        .then((response) => {
          this.responsePayload = response || {};
          this.$emit('cancelled', response || {});
        })
        .catch((err) => {
          this.error = err?.message || this.i18n.generic_error;
        })
        .finally(() => {
          this.saving = false;
        });
    },
    close() {
      this.$emit('close');
    },
    formatDateRange(startStr, endStr) {
      if (!startStr) {
        return this.fallbackDash;
      }
      const start = window.dayjs(startStr);
      const dateFormat = this.i18n.date_format || 'DD/MM/YY';
      const dateTimeFormat = this.i18n.date_time_format || 'DD/MM/YY HH:mm';
      if (!endStr) {
        return start.isValid() ? start.format(dateTimeFormat) : startStr;
      }
      const end = window.dayjs(endStr);
      if (!start.isValid() || !end.isValid()) {
        return `${startStr} - ${endStr}`;
      }
      const startLabel = start.format(dateFormat);
      const endLabel = end.format(dateFormat);
      return startLabel === endLabel
        ? start.format(dateTimeFormat)
        : `${startLabel} - ${endLabel}`;
    }
  }
};
</script>

<style scoped>
.bookaro-policy-panel {
  border: 1px solid var(--bookaro-booking-slot_border, #e5e7eb);
  border-radius: 16px;
  padding: 14px 16px;
  background: rgba(248, 250, 252, 0.9);
  display: grid;
  gap: 10px;
  margin-bottom: 16px;
}

.bookaro-policy-panel.is-blocked {
  border-color: rgba(220, 38, 38, 0.24);
  background: rgba(254, 242, 242, 0.92);
}

.bookaro-policy-panel.is-success {
  border-color: rgba(5, 150, 105, 0.24);
  background: rgba(236, 253, 245, 0.92);
}

.bookaro-policy-summary {
  margin: 0;
  font-weight: 600;
  color: #111827;
}

.bookaro-policy-copy {
  display: grid;
  gap: 4px;
  color: #374151;
  font-size: 0.92rem;
}

.bookaro-policy-copy__label {
  font-size: 0.72rem;
  font-weight: 700;
  text-transform: uppercase;
  letter-spacing: 0.08em;
  color: var(--bookaro-booking-secondary, #6b7280);
}

.bookaro-field-group {
  display: grid;
  gap: 8px;
  margin-bottom: 16px;
}

.bookaro-policy-error {
  margin-bottom: 14px;
  border: 1px solid rgba(220, 38, 38, 0.24);
  border-radius: 12px;
  padding: 10px 12px;
  background: rgba(254, 242, 242, 0.92);
  color: #991b1b;
  font-size: 0.92rem;
}
</style>
