<template>
  <div class="relative cst-book-min-cont-hei">
    <div class="flex items-center justify-between mb-4">
      <h2 class="text-2xl bk_cst_table_title font-bold">
        {{ i18n.services_tab }}
      </h2>
      <button
        @click="refresh"
        class="bookaro-btn bookaro-btn--outline"
      >
        {{ i18n.refresh }}
      </button>
    </div>

    <div v-if="loading" class="bookaro-loading-shell">
      <div class="bookaro-skeleton-card">
        <div class="bookaro-skeleton bookaro-skeleton-line is-wide"></div>
        <div class="bookaro-skeleton bookaro-skeleton-line is-medium"></div>
        <div class="bookaro-skeleton bookaro-skeleton-line is-short"></div>
      </div>
      <div class="bookaro-skeleton-card">
        <div class="bookaro-skeleton bookaro-skeleton-line is-wide"></div>
        <div class="bookaro-skeleton bookaro-skeleton-line"></div>
        <div class="bookaro-skeleton bookaro-skeleton-line"></div>
        <div class="bookaro-skeleton bookaro-skeleton-line is-medium"></div>
      </div>
    </div>

    <template v-else>
    <div v-if="!usesProviderScopedServices" class="bookaro-card bookaro-card__body mb-6">
      <label class="block text-sm font-medium text-gray-700 mb-1">
        {{ i18n.listing_label }}
      </label>
      <select
        v-model="selectedListingId"
        class="bookaro-select w-full sm:max-w-xl"
      >
        <option value="">{{ i18n.select_listing }}</option>
        <option v-for="listing in listings" :key="listing.id" :value="String(listing.id)">
          {{ formatListingLabel(listing) }}
        </option>
      </select>
      <div
        v-if="showNoListingsState"
        class="mt-3 rounded-lg border border-amber-200 bg-amber-50 p-3"
      >
        <h4 class="text-sm font-semibold text-amber-900">
          {{ i18n.empty_no_listings_title || i18n.no_listings }}
        </h4>
        <p class="mt-1 text-sm text-amber-800">
          {{ i18n.empty_no_listings_desc || i18n.no_listings }}
        </p>
        <div class="mt-2 flex flex-wrap gap-2">
          <a
            v-if="createListingUrl"
            :href="createListingUrl"
            class="bookaro-btn bookaro-btn--primary"
          >
            {{ i18n.empty_action_create_listing || i18n.empty_no_listings_title || i18n.setup_action_browse }}
          </a>
          <button
            @click="openSettingsTab"
            class="bookaro-btn bookaro-btn--outline"
          >
            {{ i18n.setup_action_settings || i18n.empty_action_open_settings }}
          </button>
          <a
            v-if="browseUrl"
            :href="browseUrl"
            class="bookaro-btn bookaro-btn--outline"
          >
            {{ i18n.setup_action_browse || i18n.empty_action_browse_site }}
          </a>
        </div>
      </div>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
      <div class="lg:col-span-2">
        <div class="bookaro-card relative">
          <div class="bookaro-card__header">
            <h3 class="text-lg font-semibold">
              {{ i18n.services_title }}
            </h3>
            <span class="text-sm text-gray-500">
              {{ services.length }} {{ i18n.entries }}
            </span>
          </div>

          <div class="bookaro-card__body">
            <div v-if="servicesLoading" class="bookaro-loading-shell">
              <div class="bookaro-skeleton-card">
                <div class="bookaro-skeleton bookaro-skeleton-line is-wide"></div>
                <div class="bookaro-skeleton bookaro-skeleton-line"></div>
                <div class="bookaro-skeleton bookaro-skeleton-line is-short"></div>
              </div>
              <div class="bookaro-skeleton-card">
                <div class="bookaro-skeleton bookaro-skeleton-line is-wide"></div>
                <div class="bookaro-skeleton bookaro-skeleton-line"></div>
                <div class="bookaro-skeleton bookaro-skeleton-line is-short"></div>
              </div>
            </div>
            <div v-else>
              <div v-if="!usesProviderScopedServices && !selectedListingId" class="text-sm text-gray-500">
                {{ i18n.select_listing }}
              </div>

              <div v-else>
                <div v-if="listError" class="text-sm text-red-600 mb-3">
                  {{ listError }}
                </div>

                <div v-if="services.length" class="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div
                    v-for="service in services"
                    :key="service.id"
                    class="bookaro-card bookaro-card__body"
                  >
                  <div class="flex items-start justify-between gap-3">
                    <div>
                      <div class="font-semibold text-gray-900">
                        {{ service.title }}
                      </div>
                      <div v-if="service.description" class="text-sm text-gray-500 mt-1">
                        {{ service.description }}
                      </div>
                    </div>
                    <div class="text-right text-sm text-gray-600">
                      <div>
                        {{ service.price_formatted || formatPrice(service.price) || i18n.placeholder_dash }}
                      </div>
                      <div>
                        {{ formatDuration(service.duration) }}
                      </div>
                    </div>
                  </div>
                  <div class="mt-3 flex items-center gap-2">
                    <button
                      @click="editService(service)"
                      class="bookaro-btn bookaro-btn--primary"
                    >
                      {{ i18n.edit }}
                    </button>
                    <button
                      @click="deleteService(service)"
                      :disabled="deleting[service.id]"
                      class="bookaro-btn bookaro-btn--danger"
                    >
                      <span v-if="deleting[service.id]">{{ i18n.deleting }}</span>
                      <span v-else>{{ i18n.delete }}</span>
                    </button>
                  </div>
                  </div>
                </div>

                <div
                  v-else
                  class="rounded-lg border border-sky-100 bg-sky-50/70 p-4"
                >
                  <h4 class="text-sm font-semibold text-sky-900">
                    {{ i18n.empty_no_services_title || i18n.no_services }}
                  </h4>
                  <p class="mt-1 text-sm text-sky-800">
                    {{ i18n.empty_no_services_desc || i18n.no_services }}
                  </p>
                  <div class="mt-3 flex flex-wrap gap-2">
                    <button
                      @click="focusServiceTitle"
                      class="bookaro-btn bookaro-btn--primary"
                    >
                      {{ i18n.empty_action_add_service || i18n.new_service }}
                    </button>
                    <a
                      v-if="selectedListingUrl"
                      :href="selectedListingUrl"
                      class="bookaro-btn bookaro-btn--outline"
                    >
                      {{ i18n.empty_action_open_listing || i18n.setup_action_preview }}
                    </a>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div>
        <div class="bookaro-card bookaro-card__body">
          <h3 class="text-lg font-semibold mb-4">{{ formTitle }}</h3>
          <form @submit.prevent="saveService">
            <div class="mb-3">
              <label class="block text-sm font-medium text-gray-700 mb-1">
                {{ i18n.service_name }}
              </label>
              <input
                ref="serviceTitleInput"
                v-model.trim="form.title"
                type="text"
                class="bookaro-input w-full"
                required
              />
            </div>
            <div class="mb-3">
              <label class="block text-sm font-medium text-gray-700 mb-1">
                {{ i18n.description_label }}
              </label>
              <textarea
                v-model.trim="form.description"
                rows="3"
                class="bookaro-textarea w-full"
              ></textarea>
            </div>
            <div class="mb-3">
              <label class="block text-sm font-medium text-gray-700 mb-1">
                {{ i18n.price_label }}
              </label>
              <input
                v-model.number="form.price"
                type="number"
                min="0"
                step="0.01"
                class="bookaro-input w-full"
              />
            </div>
            <div class="mb-4">
              <label class="block text-sm font-medium text-gray-700 mb-1">
                {{ i18n.duration_label }}
              </label>
              <input
                v-model.number="form.duration"
                type="number"
                min="0"
                step="1"
                class="bookaro-input w-full"
              />
            </div>

            <div class="flex items-center gap-2">
              <button
                type="submit"
                :disabled="saving || !canSubmit"
                class="bookaro-btn bookaro-btn--primary"
              >
                <svg
                  v-if="saving"
                  class="animate-spin h-4 w-4 mr-2"
                  viewBox="0 0 24 24"
                >
                  <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"/>
                  <path
                    class="opacity-75"
                    fill="currentColor"
                    d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z"
                  />
                </svg>
                {{ saving ? (i18n.saving_label || i18n.saving) : (i18n.save) }}
              </button>
              <button
                v-if="form.id"
                type="button"
                @click="resetForm()"
                class="bookaro-btn bookaro-btn--outline"
              >
                {{ i18n.cancel }}
              </button>
            </div>

            <p v-if="formError" class="mt-3 text-red-600">
              {{ formError }}
            </p>
            <p v-if="formMessage" class="mt-3 text-green-600">
              {{ formMessage }}
            </p>
          </form>
        </div>
      </div>
    </div>
    </template>
  </div>
</template>

<script>
export default {
  name: 'ProviderServicesView',
  props: {
    i18n: { type: Object, required: true }
  },
  data() {
    return {
      listings: [],
      services: [],
      selectedListingId: '',
      loading: false,
      servicesLoading: false,
      saving: false,
      deleting: {},
      listError: '',
      formError: '',
      formMessage: '',
      form: {
        id: 0,
        title: '',
        description: '',
        price: '',
        duration: ''
      }
    };
  },
  computed: {
    setupData() {
      return window.BookaroData?.setup || null;
    },
    createListingUrl() {
      return this.setupData?.create_listing_url || '';
    },
    browseUrl() {
      return this.setupData?.browse_url || '';
    },
    showNoListingsState() {
      return !this.loading && this.listings.length === 0;
    },
    selectedListing() {
      if (!this.selectedListingId) {
        return null;
      }
      return this.listings.find(listing => String(listing.id) === String(this.selectedListingId)) || null;
    },
    selectedListingUrl() {
      if (this.usesProviderScopedServices) {
        return this.setupData?.listing_url || this.browseUrl || '';
      }
      return this.selectedListing?.url || '';
    },
    siteType() {
      const setupType = this.setupData?.site_type || '';
      const dataType = window.BookaroData?.site_type || '';
      const siteType = String(setupType || dataType || 'directory').trim();
      return siteType || 'directory';
    },
    usesProviderScopedServices() {
      return this.siteType === 'single_business';
    },
    formTitle() {
      return this.form.id
        ? (this.i18n.edit_service)
        : (this.i18n.new_service);
    },
    canSubmit() {
      if (this.usesProviderScopedServices) {
        return String(this.form.title || '').trim().length > 0;
      }
      return !!this.selectedListingId && String(this.form.title || '').trim().length > 0;
    }
  },
  watch: {
    selectedListingId() {
      if (this.usesProviderScopedServices) {
        return;
      }
      this.resetForm();
      this.fetchServices();
    }
  },
  methods: {
    async request(path, options = {}) {
      const base = window.BookaroData?.rest_url || '/wp-json/';
      let rel = path.replace(/^\//, '');
      // Plain-permalink rest_url ("…/index.php?rest_route=/") already has a "?", so a
      // query "?" in the path must become "&" or the request 404s. (Pretty permalinks
      // have no "?" in the base, so the path is left untouched.)
      if (base.indexOf('?') !== -1) {
        rel = rel.replace('?', '&');
      }
      const url = path.startsWith('http') ? path : `${base}${rel}`;
      const headers = {
        'X-WP-Nonce': window.BookaroData?.rest_nonce || '',
        ...(options.headers || {})
      };
      const config = {
        credentials: 'same-origin',
        ...options,
        headers
      };
      const res = await fetch(url, config);
      const data = await res.json();
      if (!res.ok) {
        const message = data?.message || data?.data || this.i18n.generic_error;
        throw new Error(message);
      }
      return data;
    },
    async fetchListings() {
      if (this.usesProviderScopedServices) {
        this.loading = false;
        this.listError = '';
        this.listings = [];
        this.selectedListingId = '';
        await this.fetchServices();
        return;
      }
      this.loading = true;
      this.listError = '';
      const previousListingId = this.selectedListingId;
      try {
        const data = await this.request('bookaro/v1/provider/listings');
        this.listings = Array.isArray(data) ? data : [];
        if (this.selectedListingId) {
          const exists = this.listings.some(l => String(l.id) === String(this.selectedListingId));
          if (!exists) {
            this.selectedListingId = '';
          }
        }
        if (!this.selectedListingId && this.listings.length) {
          this.selectedListingId = String(this.listings[0].id);
        }
        if (!this.listings.length) {
          this.services = [];
        } else if (this.selectedListingId && this.selectedListingId === previousListingId) {
          this.fetchServices();
        }
      } catch (err) {
        this.listError = err.message || this.i18n.fetch_error;
        this.$emit('open-error', this.listError);
        this.listings = [];
        this.services = [];
      } finally {
        this.loading = false;
      }
    },
    async fetchServices() {
      if (!this.usesProviderScopedServices && !this.selectedListingId) {
        this.services = [];
        return;
      }
      this.servicesLoading = true;
      this.listError = '';
      try {
        let data = [];
        if (this.usesProviderScopedServices) {
          data = await this.request('bookaro/v1/provider/services/provider');
        } else {
          const query = new URLSearchParams({ listing_id: this.selectedListingId }).toString();
          data = await this.request(`bookaro/v1/provider/services?${query}`);
        }
        this.services = Array.isArray(data) ? data : [];
        this.services.sort((a, b) => String(a?.title || '').localeCompare(String(b?.title || '')));
      } catch (err) {
        this.listError = err.message || this.i18n.services_load_error;
        this.$emit('open-error', this.listError);
        this.services = [];
      } finally {
        this.servicesLoading = false;
      }
    },
    refresh() {
      if (this.usesProviderScopedServices) {
        this.fetchServices();
        return;
      }
      this.fetchListings();
    },
    focusServiceTitle() {
      this.$nextTick(() => {
        const field = this.$refs.serviceTitleInput;
        if (field && typeof field.focus === 'function') {
          field.focus();
        }
      });
    },
    openSettingsTab() {
      window.location.hash = '#settings';
    },
    editService(service) {
      this.formMessage = '';
      this.formError = '';
      this.form = {
        id: service.id,
        title: service.title || '',
        description: service.description || '',
        price: service.price,
        duration: service.duration
      };
    },
    resetForm(preserveMessage = false) {
      this.form = {
        id: 0,
        title: '',
        description: '',
        price: '',
        duration: ''
      };
      this.formError = '';
      if (!preserveMessage) {
        this.formMessage = '';
      }
    },
    async saveService() {
      this.formError = '';
      this.formMessage = '';
      if (!this.usesProviderScopedServices && !this.selectedListingId) {
        this.formError = this.i18n.listing_required;
        this.$emit('open-error', this.formError);
        return;
      }
      if (!String(this.form.title || '').trim()) {
        this.formError = this.i18n.service_title_required;
        return;
      }

      const payload = {
        title: String(this.form.title || '').trim(),
        description: String(this.form.description || ''),
        price: Number(this.form.price || 0),
        duration: Number(this.form.duration || 0)
      };
      if (!this.usesProviderScopedServices) {
        payload.listing_id = Number(this.selectedListingId);
      }

      const isEdit = !!this.form.id;
      const endpoint = this.usesProviderScopedServices
        ? (isEdit
          ? `bookaro/v1/provider/services/provider/${this.form.id}`
          : 'bookaro/v1/provider/services/provider')
        : (isEdit
          ? `bookaro/v1/provider/services/${this.form.id}`
          : 'bookaro/v1/provider/services');
      const method = isEdit ? 'PATCH' : 'POST';

      this.saving = true;
      try {
        const service = await this.request(endpoint, {
          method,
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(payload)
        });
        const idx = this.services.findIndex(s => s.id === service.id);
        if (idx >= 0) {
          this.services[idx] = service;
        } else {
          this.services.push(service);
        }
        this.services.sort((a, b) => String(a.title || '').localeCompare(String(b.title || '')));
        this.formMessage = this.i18n.service_saved;
        this.resetForm(true);
      } catch (err) {
        this.formError = err.message || this.i18n.save_failed;
        this.$emit('open-error', this.formError);
      } finally {
        this.saving = false;
      }
    },
    async deleteService(service) {
      if (!service || !service.id) {
        return;
      }
      const confirmText = this.i18n.confirm_delete_service;
      if (!window.confirm(confirmText)) {
        return;
      }
      this.deleting[service.id] = true;
      try {
        const endpoint = this.usesProviderScopedServices
          ? `bookaro/v1/provider/services/provider/${service.id}`
          : `bookaro/v1/provider/services/${service.id}`;
        await this.request(endpoint, {
          method: 'DELETE'
        });
        this.services = this.services.filter(item => item.id !== service.id);
        if (this.form.id === service.id) {
          this.resetForm(true);
        }
        this.formMessage = this.i18n.service_deleted;
      } catch (err) {
        this.formError = err.message || this.i18n.delete_failed;
        this.$emit('open-error', this.formError);
      } finally {
        delete this.deleting[service.id];
      }
    },
    formatDuration(duration) {
      const value = Number(duration || 0);
      if (!value) {
        return this.i18n.placeholder_dash;
      }
      return `${value} ${this.i18n.minutes_label}`;
    },
    formatPrice(value) {
      const settings = window.BookaroData?.currency || {};
      const num = Number(value);
      if (Number.isNaN(num)) {
        return '';
      }
      const decimals = Number.isInteger(settings.decimals) ? settings.decimals : 2;
      const decSep = settings.decimal_separator || '.';
      const thouSep = settings.thousand_separator || ',';
      const symbol = settings.symbol || '';
      const format = settings.format || '%1$s%2$s';
      const fixed = num.toFixed(decimals);
      const parts = fixed.split('.');
      const intPart = parts[0].replace(/\\B(?=(\\d{3})+(?!\\d))/g, thouSep);
      const number = parts[1] !== undefined ? intPart + decSep + parts[1] : intPart;
      return format.replace('%1$s', symbol).replace('%2$s', number);
    },
    formatListingLabel(listing) {
      const title = listing?.title || this.i18n.untitled;
      const status = listing?.status && listing.status !== 'publish' ? ` (${listing.status})` : '';
      return `${title}${status}`;
    }
  },
  mounted() {
    if (this.usesProviderScopedServices) {
      this.fetchServices();
      return;
    }
    this.fetchListings();
  }
};
</script>
